-
Notifications
You must be signed in to change notification settings - Fork 19
/
2.1-Remove_Dups.py
81 lines (63 loc) · 1.65 KB
/
2.1-Remove_Dups.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# CTCI 2.1
# Remove Dups
import unittest
# Uh this isn't working?
from LinkedList import LinkedList
# My Solution
def remove_dups(head):
unique = []
# Initialize prev and curr - return if 1 or 0 element list
if head and head.next:
prev = head
curr = head.next
unique.append(prev.val)
else:
return head
# Iterate through list adding each unique value to the list
while curr:
if curr.val not in unique:
unique.append(curr.val)
curr = curr.next
prev = prev.next
else:
curr = curr.next
prev.next = curr
return head
#-------------------------------------------------------------------------------
# CTCI Solution
def remove_dups2(ll):
if ll.head is None:
return
current = ll.head
seen = set([current.value])
while current.next:
if current.next.value in seen:
current.next = current.next.next
else:
seen.add(current.next.value)
current = current.next
return ll
def remove_dups_followup(ll):
if ll.head is None:
return
current = ll.head
while current:
runner = current
while runner.next:
if runner.next.value == current.value:
runner.next = runner.next.next
else:
runner = runner.next
current = current.next
return ll.head
#-------------------------------------------------------------------------------
#Testing
ll = LinkedList()
ll.generate(100, 0, 9)
print(ll)
remove_dups(ll)
print(ll)
ll.generate(100, 0, 9)
print(ll)
remove_dups_followup(ll)
print(ll)