Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Singly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
currentNode = self.head
while currentNode:
print(currentNode.data)
# quit()
currentNode = currentNode.next
def prepend(self,data):
newNode = Node(data)
newNode.next = self.head
self.head = newNode
def insertAfter(self, previousNode, data):
if not previousNode:
print('send prev node')
return
newNode = Node(data)
newNode.next = previousNode.next
previousNode.next = newNode
def append(self, data):
newNode = Node(data);
if self.head is None:
self.head = newNode
return;
lastNode = self.head
while lastNode.next:
lastNode = lastNode.next
lastNode.next = newNode;
llist = LinkedList()
llist.append("A")
llist.append("B")
llist.append("C")
llist.prepend("D")
llist.insertAfter(llist.head.next,"E")
llist.display()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment