Python Program For Rotating A Linked List
Last Updated :
18 May, 2022
Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smaller than the count of nodes in a linked list.
Method 1:
To rotate the linked list, we need to change the next of kth node to NULL, the next of the last node to the previous head node, and finally, change the head to (k+1)th node. So we need to get hold of three nodes: kth node, (k+1)th node, and last node.
Traverse the list from the beginning and stop at kth node. Store pointer to kth node. We can get (k+1)th node using kthNode->next. Keep traversing till the end and store a pointer to the last node also. Finally, change pointers as stated above.
Below image shows how to rotate function works in the code :
Python
# Python program to rotate
# a linked list
# Node class
class Node:
# Constructor to initialize
# the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node
# at the beginning
def push(self, new_data):
# allocate node and put the data
new_node = Node(new_data)
# Make next of new node as head
new_node.next = self.head
# Move the head to point to the
# new Node
self.head = new_node
# Utility function to print it the
# linked LinkedList
def printList(self):
temp = self.head
while(temp):
print temp.data,
temp = temp.next
# This function rotates a linked list
# counter-clockwise and updates the
# head. The function assumes that k
# is smaller than size of linked list.
# It doesn't modify the list if k is
# greater than of equal to size
def rotate(self, k):
if k == 0:
return
# Let us understand the below code
# for example k = 4 and list =
# 10->20->30->40->50->60
current = self.head
# current will either point to kth
# or NULL after this loop current
# will point to node 40 in the above
# example
count = 1
while(count <k and
current is not None):
current = current.next
count += 1
# If current is None, k is greater
# than or equal to count of nodes
# in linked list. Don't change
# the list in this case
if current is None:
return
# current points to kth node. Store
# it in a variable kth node points
# to node 40 in the above example
kthNode = current
# current will point to last node
# after this loop current will point
# to node 60 in above example
while(current.next is not None):
current = current.next
# Change next of last node to previous
# head Next of 60 is now changed to
# node 10
current.next = self.head
# Change head to (k + 1)th node
# head is not changed to node 50
self.head = kthNode.next
# change next of kth node to NULL
# next of 40 is not NULL
kthNode.next = None
# Driver code
llist = LinkedList()
# Create a list
# 10->20->30->40->50->60
for i in range(60, 0, -10):
llist.push(i)
print "Given linked list"
llist.printList()
llist.rotate(4)
print "Rotated Linked list"
llist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
p>
Output:
Given linked list
10 20 30 40 50 60
Rotated Linked list
50 60 10 20 30 40
Time Complexity: O(n) where n is the number of nodes in Linked List. The code traverses the linked list only once.
Method 2:
To rotate a linked list by k, we can first make the linked list circular and then moving k-1 steps forward from head node, making (k-1)th node's next to null and make kth node as head.
[tabby title="Python3"]
python3
# Python3 program to rotate a
# linked list counter clock wise
# Link list node
class Node:
def __init__(self):
self.data = 0
self.next = None
# This function rotates a linked list
# counter-clockwise and updates the
# head. The function assumes that k is
# smaller than size of linked list.
def rotate(head_ref, k):
if (k == 0):
return
# Let us understand the below
# code for example k = 4 and
# list = 10.20.30.40.50.60.
current = head_ref
# Traverse till the end.
while (current.next != None):
current = current.next
current.next = head_ref
current = head_ref
# Traverse the linked list to k-1
# position which will be last
# element for rotated array.
for i in range(k - 1):
current = current.next
# Update the head_ref and last
# element pointer to None
head_ref = current.next
current.next = None
return head_ref
# UTILITY FUNCTIONS
# Function to push a node
def push(head_ref, new_data):
# Allocate node
new_node = Node()
# Put in the data
new_node.data = new_data
# Link the old list off
# the new node
new_node.next = (head_ref)
# Move the head to point
# to the new node
(head_ref) = new_node
return head_ref
# Function to print linked list
def printList(node):
while (node != None):
print(node.data, end = ' ')
node = node.next
# Driver code
if __name__=='__main__':
# Start with the empty list
head = None
# Create a list
# 10.20.30.40.50.60
for i in range(60, 0, -10):
head = push(head, i)
print("Given linked list ")
printList(head)
head = rotate(head, 4)
print("\nRotated Linked list ")
printList(head)
# This code is contributed by rutvik_56
Output:
Given linked list
10 20 30 40 50 60
Rotated Linked list
50 60 10 20 30 40
Please refer complete article on
Rotate a Linked List for more details!
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read