Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # program to reverse a linked list
- class LinkedList:
- def __init__(self):
- self.head = None
- # 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()), end=" ")
- start = start.link
- if start:
- print("-->", end=" ")
- print()
- # method reverses the LinkedList
- def reverse(self):
- start = self.head
- tempNode = None
- previousNode = None
- while start:
- tempNode = start.getNextNode()
- start.setLink(previousNode)
- previousNode = start
- start = tempNode
- self.head = previousNode
- return True
- # 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
- print("Program to reverse the Linked List")
- # creating LinkedList
- myList = LinkedList()
- myList.addToStart(1)
- myList.addToEnd(2)
- myList.addToEnd(3)
- myList.addToEnd(4)
- myList.addToEnd(5)
- myList.addToEnd(6)
- myList.addToEnd(7)
- myList.addToEnd(8)
- myList.addToEnd(9)
- myList.addToEnd(10)
- myList.addToEnd(11)
- myList.display()
- print("Linked List after Reversing is : ")
- # reversing the LinkedLkst
- myList.reverse()
- myList.display()
Add Comment
Please, Sign In to add comment