Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # program to implement Linked List
- class LinkedList:
- def __init__(self):
- self.head = None
- # returns true is LinkedList is Empty
- def isEmpty(self):
- if self.head is None:
- return True
- else:
- return False
- # method adds elements to the left of the Linked List
- def addToStart(self, data):
- # create a temporary node
- tempNode = Node(data)
- tempNode.setLink(self.head)
- self.head = tempNode
- del tempNode
- # method adds elements to the right of the Linked List
- def addToEnd(self, data):
- start = self.head
- tempNode = Node(data)
- while start.getNextNode():
- start = start.getNextNode()
- start.setLink(tempNode)
- del tempNode
- return True
- # method displays Linked List
- def display(self):
- start = self.head
- if start is None:
- print("Empty List!!!")
- return False
- while start:
- print(str(start.getData()))
- start = start.link
- print()
- # method pushes element to the Linked List
- def push(self, data):
- self.addToStart(data)
- return True
- # method removes and returns the last element from the Linked List
- def pop(self):
- if self.isEmpty():
- return False
- start = self.head
- data = start.getData()
- start = start.getNextNode()
- self.head = start
- return data
- # node class
- class Node:
- # default value of data and link is none if no data is passed
- def __init__(self, data=None, link=None):
- self.data = data
- self.link = link
- # method to update the data feild of Node
- def updateData(self, data):
- self.data = data
- # method to set Link feild the Node
- def setLink(self, node):
- self.link = node
- # method returns data feild of the Node
- def getData(self):
- return self.data
- # method returns address of the next Node
- def getNextNode(self):
- return self.link
- # main method
- # creating LinkedList
- myList = LinkedList()
- # adding some elements to the start of LinkedList
- myList.push(1)
- myList.push(2)
- myList.push(3)
- myList.push(4)
- myList.push(5)
- myList.push(6)
- print("The Contents of the stack are : ")
- myList.display()
- # adding some elements to the End of the LinkedList
- print("Removing 3 elements from the stack\n")
- myList.pop()
- myList.pop()
- myList.pop()
- print("The Contents of the stack are : ")
- myList.display()
Add Comment
Please, Sign In to add comment