Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # program to rotate 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()), end=" ")
- start = start.link
- if start:
- print("-->", end=" ")
- print()
- # rotate a linked list
- # function removes nodes from the beginning and puts them to the end of the linked list;
- def rotate(self, shiftValue):
- current = self.head
- tail = self.head
- # make tail point the last element
- while tail.getNextNode() is not None:
- tail = tail.getNextNode()
- for i in range(shiftValue):
- tail.setLink(current)
- current = current.getNextNode()
- tail = tail.getNextNode()
- tail.setLink(None)
- # let head point to the new head node
- self.head = current
- return
- # 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()
- 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)
- print("Program to rotate linked list elements")
- myList.display()
- print("\nRotating linked list by 4 places")
- myList.rotate(4)
- myList.display()
Add Comment
Please, Sign In to add comment