Skip to main content

Rotate a linked list by k nodes in python

Python program for Rotate a linked list by k nodes. Here problem description and other solutions.

#  Python 3 program for
#  Rotate a linked list

#  Linked list node
class LinkNode :
	def __init__(self, data) :
		self.data = data
		self.next = None

class SingleLL :
	def __init__(self) :
		self.head = None
		self.tail = None
	
	#  Add new node at the end of linked list
	def insert(self, value) :
		#  Create a new node
		node = LinkNode(value)
		if (self.head == None) :
			self.head = node
		else :
			self.tail.next = node
		self.tail = node
	
	#  Display linked list element
	def display(self) :
		if (self.head == None) :
			return
		
		temp = self.head
		#  iterating linked list elements
		while (temp != None) :
			print(temp.data , end = " → ")
			#  Visit to next node
			temp = temp.next
		
		print("NULL")
	
	def validKNode(self, k) :
		temp = self.head
		count = 0
		#  Count node
		while (temp != None) :
			count += 1
			if (count > k) :
				#  When K is correct
				return k
			
			#  Visit to next node
			temp = temp.next
		
		#  Need to change k value
		return k % count
	
	def rotate(self, k) :
		if (k <= 0) :
			return
		
		if (self.head == None) :
			print("Empty linked list")
			return
		
		#  Assume that k is less the number of nodes
		#  Otherwise first count number of nodes 
		#  Then use modulo operator and change k = k % count
		#  Here implement
		k = self.validKNode(k)
		if (k == 0) :
			#  because after rotate get same result
			return
		else :
			#  Use to find the location of rotate node
			counter = 1
			point = None
			temp = self.head
			#  Find last node in rotation
			while (temp != None and temp.next != None) :
				if (counter == k) :
					point = temp
				
				counter += 1
				temp = temp.next
			
			#  When roated node are exist
			if (point != None) :
				#  Modified node position
				temp.next = self.head
				#  Modified head
				self.head = point.next
				#  Modified tail
				self.tail = point
				point.next = None
			
		
	

def main() :
	sll = SingleLL()
	k = 3
	#  Linked list
	#  1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
	sll.insert(1)
	sll.insert(2)
	sll.insert(3)
	sll.insert(4)
	sll.insert(5)
	sll.insert(6)
	sll.insert(7)
	sll.insert(8)
	print("Before Rotate ", k ," Nodes")
	sll.display()
	#  Rotate node
	sll.rotate(k)
	print("After Rotate ", k ," Nodes")
	sll.display()

if __name__ == "__main__": main()

Output

Before Rotate  3  Nodes
1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
After Rotate  3  Nodes
4 → 5 → 6 → 7 → 8 → 1 → 2 → 3 → NULL




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment