Monday, April 25, 2016

Singly Linked List Implementation in python

Below is a very simplistic implementation of a singly linked list. The linked list implementation is done using two classes Node and LinkedList. Node is a class representing each node of the linked list and LinkedList is a class representing the whole linked list itself.
# !/usr/bin/python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def AddNode(self, data):
temp = Node(data)
if self.head == None:
self.head = temp
self.tail = temp
else:
self.tail.next = temp
self.tail = temp
def RemoveNode(self, index):
temp = self.head
if temp.data == index:
temp = self.head = temp.next
while ( temp.next != None):
print temp.data
if temp.next.data == index:
node = temp.next
temp.next = temp.next.next
del node
else:
temp = temp.next
def PrintList(self):
temp = self.head
while ( temp.next != None):
print temp.data,
print "->",
temp = temp.next
if(temp.next == None):
print temp.data
llist = LinkedList()
llist.AddNode(1)
llist.AddNode(2)
llist.AddNode(3)
llist.AddNode(4)
llist.AddNode(5)
llist.AddNode(6)
llist.PrintList()
llist.RemoveNode(6)
llist.PrintList()
view raw llist.py hosted with ❤ by GitHub