Created
August 14, 2016 06:03
-
-
Save humbroll/39ef7e0c9fa70e1c391b81d6b84a0c19 to your computer and use it in GitHub Desktop.
Remove Duplication in LinkedList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# Question. | |
# Write code to remove duplicates from an unsorted linked list. | |
# Follow UP | |
# How would you solve this problem if a temporary buffer is not allowed? | |
class Node: | |
def __init__(self, value, next=None): | |
self.value = value | |
self.next_ptr = next | |
def __str__(self): | |
return "%d" % (self.value) | |
class LinkedList: | |
def __init__(self): | |
self.edge_node = None | |
def add_node(self, node): | |
self.edge_node = node | |
def add(self, node_value): | |
new_node = Node(node_value, self.edge_node) | |
self.add_node(new_node) | |
return new_node | |
def remove_duplicates(self): | |
exists_vaues = [] # to Hash | |
pre_node = None | |
cur_node = self.edge_node | |
while cur_node: | |
if cur_node.value in exists_vaues: | |
pre_node.next_ptr = cur_node.next_ptr | |
else: | |
exists_vaues.append(cur_node.value) | |
pre_node = cur_node | |
cur_node = cur_node.next_ptr | |
def __str__(self): | |
node_value_arr = [] | |
node = self.edge_node | |
while node: | |
node_value_arr.append(str(node)) | |
node = node.next_ptr | |
return " -> ".join(node_value_arr) | |
if __name__ == '__main__': | |
# Setup linkedlist | |
linked_list = LinkedList() | |
node_5 = linked_list.add(5) | |
node_3_2 = linked_list.add(3) # Make duplicate | |
node_4_3 = linked_list.add(4) | |
node_4_2 = linked_list.add(4) | |
node_4 = linked_list.add(4) | |
node_3 = linked_list.add(3) | |
node_2_2 = linked_list.add(2) # Make duplicate | |
node_2 = linked_list.add(2) | |
node_1_2 = linked_list.add(1) # Make duplicate | |
node_1 = linked_list.add(1) | |
print "Before removing duplicates" | |
print linked_list | |
linked_list.remove_duplicates() | |
print "After removing duplicates" | |
print linked_list | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment