Last active
August 26, 2016 21:11
-
-
Save MattyAyOh/d3d1d2db697ab7786e44 to your computer and use it in GitHub Desktop.
Remove nodes with duplicate values from a singly-linked list
This file contains 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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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