@@ -17,8 +17,10 @@ def __init__(self, d: int):
17
17
18
18
19
19
class LinkedList :
20
- def __init__ (self ):
20
+ def __init__ (self , initial_value : int = None ):
21
21
self .head = None
22
+ if initial_value is not None :
23
+ self .head = Node (initial_value )
22
24
23
25
def append_to_tail (self , d : int ) -> None :
24
26
if self .head is None :
@@ -79,12 +81,14 @@ def remove_dups(ll: LinkedList) -> LinkedList:
79
81
:return: a linked list without duplicates
80
82
"""
81
83
n = ll .head
82
- unique_vals = set ()
83
- while n .next is not None :
84
+ unique_vals = {n .data } # set literal
85
+ output_ll = LinkedList (n .data )
86
+ while n is not None :
87
+ if n .data not in unique_vals :
88
+ output_ll .append_to_tail (n .data )
84
89
unique_vals .add (n .data )
85
90
n = n .next
86
- unique_vals .add (n .data )
87
- return build_linked_list (list (unique_vals ))
91
+ return output_ll
88
92
89
93
90
94
def remove_dups_no_buffer (ll : LinkedList ) -> LinkedList :
@@ -109,11 +113,10 @@ def remove_dups_no_buffer(ll: LinkedList) -> LinkedList:
109
113
# re-arrange pointers to omit
110
114
# the duplicate
111
115
prev .next = m .next
112
- m = prev .next
113
116
else :
114
117
# otherwise, advance m and prev pointers
115
118
prev = m
116
- m = m .next
119
+ m = prev .next
117
120
n = n .next
118
121
return ll
119
122
@@ -150,6 +153,18 @@ def setUp(self):
150
153
build_linked_list ([1 , 1 , 3 , 4 , 5 , 5 , 6 , 7 ]),
151
154
build_linked_list ([1 , 3 , 4 , 5 , 6 , 7 ])
152
155
),
156
+ (
157
+ build_linked_list ([7 , 2 , 7 , 9 , 20 , 1 , 0 , 0 , 0 , 25 ]),
158
+ build_linked_list ([7 , 2 , 9 , 20 , 1 , 0 , 25 ])
159
+ ),
160
+ (
161
+ build_linked_list ([9 , 8 , 7 , 6 , 6 , 1 , 2 , 3 , 4 , 4 ]),
162
+ build_linked_list ([9 , 8 , 7 , 6 , 1 , 2 , 3 , 4 ])
163
+ ),
164
+ (
165
+ build_linked_list ([9 , 9 , 9 , - 10 , - 100 , 45 , 67 , - 100 , 99 ]),
166
+ build_linked_list ([9 , - 10 , - 100 , 45 , 67 , 99 ])
167
+ )
153
168
]
154
169
155
170
def test_remove_dups (self ):
0 commit comments