Skip to content

Fixing Ch2-1 when the duplicate element is in the last position #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 18 additions & 12 deletions Ch2. Linked-Lists/Ch2 -1 Remove duplicate.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,21 @@
import unittest

def remove_duplicates(head):
nodes = {}
node = head
while(node!=None):
if node.data in nodes.keys():
node.data = node.next.data
node.next = node.next.next
else:
nodes[node.data] = 1
node = node.next

return head
prev_element = head
next_element = head.next
elements = [head.data]
while next_element is not None:
if next_element.data in elements:
if next_element.next is None:
prev_element.next = None
next_element = None
else:
prev_element.next = next_element.next
next_element = prev_element.next
else:
elements.append(next_element.data)
prev_element = next_element
next_element = next_element.next



Expand All @@ -28,10 +32,12 @@ class Test(unittest.TestCase):
def test_remove_duplicates(self):
head = Node(1,Node(3,Node(3,Node(1,Node(5,None)))))
remove_duplicates(head)
head = Node(1,Node(3,Node(3,None)))
remove_duplicates(head)
self.assertEqual(head.data, 1)
self.assertEqual(head.next.data, 3)
self.assertEqual(head.next.next.data, 5)
self.assertEqual(head.next.next.next, None)


unittest.main()
unittest.main()