Skip to content

Instantly share code, notes, and snippets.

@prabhakaran9397
Last active November 7, 2018 17:55
Show Gist options
  • Save prabhakaran9397/9d91cce7d066c3b8d20902c26827e591 to your computer and use it in GitHub Desktop.
Save prabhakaran9397/9d91cce7d066c3b8d20902c26827e591 to your computer and use it in GitHub Desktop.
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
#print override
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self, head=None):
self.head = head
#generator override, can be used in for loop
def __iter__(self):
currNode = self.head
while currNode:
yield currNode
currNode = currNode.next
def __repr__(self):
#Converting generator(__iter__) into list will expose the content
#__repr__ needs return type to be of string
return str(list(self))
def insertAtFront(self, value):
self.head = Node(value, self.head)
def insertAtBack(self, value):
if self.head is None:
self.insertAtFront(value)
return
#this calls __iter__
for currNode in self:
if currNode.next is None:
break
currNode.next = Node(value)
def removeFirst(self):
if self.head is not None:
self.head = self.head.next
def removeLast(self):
if self.head is None:
return
elif self.head.next is None:
self.head = None
return
for currNode in self:
if currNode.next.next is None:
break
currNode.next = None
def main():
list = LinkedList()
list.insertAtBack(4)
list.insertAtBack(5)
#this calls __repr__
print list #[4, 5]
list.insertAtFront(3)
list.insertAtFront(2)
list.insertAtFront(1)
print list #[1, 2, 3, 4, 5]
list.insertAtBack(6)
list.insertAtBack(7)
print list #[1, 2, 3, 4, 5, 6, 7]
list.removeFirst()
print list #[2, 3, 4, 5, 6, 7]
list.removeLast()
list.removeLast()
list.removeLast()
list.removeLast()
list.removeLast()
list.removeLast()
print list #[]
list.insertAtFront(1000)
print list #[1000]
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment