Skip to content

Instantly share code, notes, and snippets.

@MattyAyOh
Last active August 26, 2016 21:11
Show Gist options
  • Save MattyAyOh/d3d1d2db697ab7786e44 to your computer and use it in GitHub Desktop.
Save MattyAyOh/d3d1d2db697ab7786e44 to your computer and use it in GitHub Desktop.
Remove nodes with duplicate values from a singly-linked list
# Write a function that takes a head node;
# then iterates through a singly-linked list starting from the head node, and remove any nodes that have duplicate values
class Node():
def __init__(self, value):
self.value = value
self.next = None
myNode1 = Node(1)
myNode2 = Node(2)
myNode3 = Node(3)
myNode4 = Node(2)
myNode5 = Node(4)
myNode1.next = myNode2
myNode2.next = myNode3
myNode3.next = myNode4
myNode4.next = myNode5
myNode5.next = null
currNode = myNode
prevNode = None
existingValues = {}
while currNode != None:
if(currNode.value in existingValues):
prevNode.next = currNode.next
else:
existingValues[currNode.value] = True
prevNode = currNode
currNode = currNode.next
@MattyAyOh
Copy link
Author

Write a function that takes a head node; then iterates through a singly-linked list starting from the head node, and remove any nodes that have duplicate values

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment