@@ -6,6 +6,47 @@ import Basics (Nat)
6
6
-- A sequence of nodes, simple very of graph
7
7
data LinkedList a = Null' | Node' a (LinkedList a ) deriving Show
8
8
9
+ instance Eq a => Eq (LinkedList a ) where
10
+ Null' == Null' = True
11
+ Null' == (Node' _ _) = False
12
+ (Node' _ _) == Null' = False
13
+ (Node' x1 x2) == (Node' y1 y2) = x1 == y1 && x2 == y2
14
+
15
+ testLink = Node' 1 $ Node' 2 $ Node' 1 $ Node' 5 $ Node' 2 $ Node' 3 Null'
16
+
17
+ {-
18
+ 2.1
19
+ Write code to remove duplicates from an unsorted linked list.
20
+
21
+ Test Case:
22
+ removeDup testLink
23
+ -}
24
+ removeDup :: Eq a => LinkedList a -> LinkedList a
25
+ removeDup xs = removeDupHelper xs []
26
+
27
+ removeDupHelper :: Eq a => LinkedList a -> [LinkedList a ] -> LinkedList a
28
+ removeDupHelper Null' _ = Null'
29
+ removeDupHelper (Node' x y) dict
30
+ | Node' x Null' `elem` dict = removeDupHelper y dict
31
+ | otherwise = Node' x (removeDupHelper y (Node' x Null' : dict))
32
+
33
+ -- (no dict)loop into the original list, and refine the result list
34
+ removeDupBF :: Eq a => LinkedList a -> LinkedList a
35
+ removeDupBF xs = removeDupBFHelper xs xs
36
+
37
+ removeDupBFHelper :: Eq a => LinkedList a -> LinkedList a -> LinkedList a
38
+ removeDupBFHelper Null' refined = refined
39
+ removeDupBFHelper _ Null' = Null'
40
+ removeDupBFHelper (Node' x l1) (Node' y l2) =
41
+ removeDupBFHelper l1 (refineLink (Node' x Null' ) (Node' y l2) True )
42
+
43
+ refineLink :: Eq a => LinkedList a -> LinkedList a -> Bool -> LinkedList a
44
+ refineLink _ Null' _ = Null'
45
+ refineLink x (Node' y l) isFirst
46
+ | (x == Node' y Null' ) && not isFirst = refineLink x l isFirst
47
+ | (x == Node' y Null' ) && isFirst = Node' y (refineLink x l False )
48
+ | otherwise = Node' y (refineLink x l isFirst)
49
+
9
50
{-
10
51
4.3 Given a binary tree, design an algorithm which creates
11
52
a linked list of all the nodes at each depth.
@@ -35,6 +76,6 @@ divideTreeHelper xs track (Just y:ys) =
35
76
-- Check whether it is belong to the set of power of two
36
77
isPowerOfTwo :: Nat -> Bool
37
78
isPowerOfTwo 1 = True
38
- isPowerOfTwo x
79
+ isPowerOfTwo x
39
80
| x `mod` 2 == 1 = False
40
81
| otherwise = isPowerOfTwo (x `div` 2 )
0 commit comments