I am trying to write a snippet for removing duplicate elements in a linked list in python.
my condition of checking previous node values in dictionary is not yielding true. I am unable to figure out why it always returns false.
Node values are [ 0->1->2->2->3->4->4->5
def RemoveRepeatNode(self):
curr_node = self.head
unique_list = {}
unique_list[curr_node.data] = 1
while(curr_node.next != None):
if curr_node.next.data in unique_list: ## doesn't evaluate to True
print "repeated values ", curr_node.next.data
curr_node = curr_node.next.next
else:
unique_list[curr_node.data] = 1
curr_node = curr_node.next
Your if clause might be fine, but you do not relink. Change:
def RemoveRepeatNode(self):
curr_node = self.head
unique = {curr_node.data} # better data structure: set
while(curr_node.next != None):
if curr_node.next.data in unique:
curr_node.next = curr_node.next.next
# ^^^^^ relink!
else:
unique.add(curr_node.next.data)
# add .next.data ^^^^^ that's the one you checked
curr_node = curr_node.next
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.