Skip to content

Commit b580c36

Browse files
committed
4 changes...
- add additional optional param to linked list constructor for initializing first value - modify remove_dups to keep data in order - unconditional m = prev.next - add 3 unsorted test cases
1 parent 74ef365 commit b580c36

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

Python/chapter02/2.1 - Remove Dups/miguel_2.1_sol.py

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,10 @@ def __init__(self, d: int):
1717

1818

1919
class LinkedList:
20-
def __init__(self):
20+
def __init__(self, initial_value: int = None):
2121
self.head = None
22+
if initial_value is not None:
23+
self.head = Node(initial_value)
2224

2325
def append_to_tail(self, d: int) -> None:
2426
if self.head is None:
@@ -79,12 +81,14 @@ def remove_dups(ll: LinkedList) -> LinkedList:
7981
:return: a linked list without duplicates
8082
"""
8183
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)
8489
unique_vals.add(n.data)
8590
n = n.next
86-
unique_vals.add(n.data)
87-
return build_linked_list(list(unique_vals))
91+
return output_ll
8892

8993

9094
def remove_dups_no_buffer(ll: LinkedList) -> LinkedList:
@@ -109,11 +113,10 @@ def remove_dups_no_buffer(ll: LinkedList) -> LinkedList:
109113
# re-arrange pointers to omit
110114
# the duplicate
111115
prev.next = m.next
112-
m = prev.next
113116
else:
114117
# otherwise, advance m and prev pointers
115118
prev = m
116-
m = m.next
119+
m = prev.next
117120
n = n.next
118121
return ll
119122

@@ -150,6 +153,18 @@ def setUp(self):
150153
build_linked_list([1, 1, 3, 4, 5, 5, 6, 7]),
151154
build_linked_list([1, 3, 4, 5, 6, 7])
152155
),
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+
)
153168
]
154169

155170
def test_remove_dups(self):

0 commit comments

Comments
 (0)