Skip to content

Instantly share code, notes, and snippets.

@olslash
Created June 19, 2014 17:43
Show Gist options
  • Save olslash/7690f9273aa3e0c9a39d to your computer and use it in GitHub Desktop.
Save olslash/7690f9273aa3e0c9a39d to your computer and use it in GitHub Desktop.
babby's first linked list
class Node:
def __init__(self, val = None):
self.value = val
self.next = None
def printValues(self):
n = self
values = [n.value]
while n.next:
n = n.next
values.append(n.value)
return values
def insertAfter(self, val):
oldNext = self.next
self.next = Node(val)
self.next.next = oldNext
def appendToTail(self, val):
n = self
while n.next:
n = n.next
n.next = Node(val)
def removeDuplicates(self):
buff = {}
previous = Node()
n = self
while n:
if(n.value in buff):
previous.next = n.next
else:
buff[n.value] = True
previous = n
n = n.next
def getKthToLast(self, k):
leader = head
follower = head
for _ in range(k-1):
leader = leader.next
while(leader.next):
leader = leader.next
follower = follower.next
return follower.value
# -----------------
head = Node(5)
head.next = Node(4)
head.appendToTail(13)
head.next.insertAfter(5)
print(head.printValues())
print(head.getKthToLast(2))
head.removeDuplicates()
print(head.printValues())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment