Python3 Program for Clockwise rotation of Linked List
Last Updated :
05 Sep, 2024
Write a Python3 program for a given singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.
Examples:
Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL, K = 2
Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULL
Input: 7 -> 9 -> 11 -> 13 -> 3 -> 5 -> NULL, K = 12
Output: 7 -> 9 -> 11 -> 13 -> 3 -> 5 -> NULL
Approach:
To rotate the linked list first check whether the given k is greater than the count of nodes in the linked list or not. Traverse the list and find the length of the linked list then compare it with k, if less then continue otherwise deduce it in the range of linked list size by taking modulo with the length of the list.
After that subtract the value of k from the length of the list. Now, the question has been changed to the left rotation of the linked list so follow that procedure:
Steps:
- Change the next of the kth node to NULL.
- Change the next of the last node to the previous head node.
- Change the head to (k+1)th node.
In order to do that, the pointers to the kth node, (k+1)th node, and last node are required.
Below is the implementation of the above approach:
Python
# Python3 implementation of the approach
''' Link list node '''
class Node:
def __init__(self, data):
self.data = data
self.next = None
''' A utility function to push a node '''
def push(head_ref, new_data):
''' allocate node '''
new_node = Node(new_data)
''' 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
''' A utility function to print linked list '''
def printList(node):
while (node != None):
print(node.data, end=' -> ')
node = node.next
print("NULL")
# Function that rotates the given linked list
# clockwise by k and returns the updated
# head pointer
def rightRotate(head, k):
# If the linked list is empty
if (not head):
return head
# len is used to store length of the linked list
# tmp will point to the last node after this loop
tmp = head
len = 1
while (tmp.next != None):
tmp = tmp.next
len += 1
# If k is greater than the size
# of the linked list
if (k > len):
k = k % len
# Subtract from length to convert
# it into left rotation
k = len - k
# If no rotation needed then
# return the head node
if (k == 0 or k == len):
return head
# current will either point to
# kth or None after this loop
current = head
cnt = 1
while (cnt < k and current != None):
current = current.next
cnt += 1
# If current is None then k is equal to the
# count of nodes in the list
# Don't change the list in this case
if (current == None):
return head
# current points to the kth node
kthnode = current
# Change next of last node to previous head
tmp.next = head
# Change head to (k+1)th node
head = kthnode.next
# Change next of kth node to None
kthnode.next = None
# Return the updated head pointer
return head
# Driver code
if __name__ == '__main__':
''' The constructed linked list is:
1.2.3.4.5 '''
head = None
head = push(head, 5)
head = push(head, 4)
head = push(head, 3)
head = push(head, 2)
head = push(head, 1)
k = 2
# Rotate the linked list
updated_head = rightRotate(head, k)
# Print the rotated linked list
printList(updated_head)
# This code is contributed by rutvik_56
Output4 -> 5 -> 1 -> 2 -> 3 -> NULL
Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.
Deque based approach :
This problem can also be solved using the deque data structure.
Approach:
Initialise a deque and push the linked list into it.
Then keep popping from it’s back and adding that node to it’s front until the number of operations are not equal to k.
Below is the implementation of the above approach:
Python
# Python Program for rotating a Linked List by k
from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.next = None
def build(head, val):
if(head == None):
head = Node(val)
else:
temp = head
while(temp.next != None):
temp = temp.next
temp.next = Node(val)
return head
def printList(node):
while(node != None):
print(node.data, end = "->")
node = node.next
print("NULL")
def rotate_clockwise(head, k):
if(head == None):
return None
q = deque([])
temp = head
while(temp != None):
q.append(temp)
temp = temp.next
k %= len(q)
while(k != 0):
q[-1].next = q[0]
q.appendleft(q[-1])
q.pop()
q[-1].next = None
k = k-1
return q[0]
head = None
head = build(head, 1)
head = build(head, 2)
head = build(head, 3)
head = build(head, 4)
head = build(head, 5)
k = 2
r = rotate_clockwise(head, k)
printList(r)
# This code is contributed by Yash Agarwal(yashagarwal2852002)
Output4->5->1->2->3->NULL
Time Complexity: O(N)
Auxiliary Space: O(N)
Please refer complete article on Clockwise rotation of Linked List for more details!
Similar Reads
Javascript Program for Clockwise rotation of Linked List Given a singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL, K = 2 Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULLInput: 7 -> 9 -> 11 -> 13 -> 3 -> 5 -> NULL
4 min read
Clockwise rotation of Linked List Given a singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL, K = 2 Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULLInput: 7 -> 9 -> 11 -> 13 -> 3 -> 5 -> NULL
15+ min read
Javascript Program For Rotating A Linked List 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 smal
5 min read
Javascript Program to Rotate Linked List block wise Given a Linked List of length n and block length k rotate in a circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left.Examples: Input: 1->2->3->4->5->6->7->8->9->NULL, k = 3 d = 1Output: 3->1->2-
3 min read
Python program to right rotate a list by n Given a list and an integer n, write a Python program to right-rotate the list by n position. Examples : Input : n = 2, List_1 = [1, 2, 3, 4, 5, 6]Output : List_1 = [5, 6, 1, 2, 3, 4]Explanation: We get output list after right rotating (clockwise) given list by 2. Input : n = 3, List_1 = [3, 0, 1, 4
6 min read
Python Program for Reversal algorithm for array rotation Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. In this article, we will explore the Reversal Algorithm for array rotation and implement it in Python. Example Input: arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output: arr[] = [3, 4, 5, 6, 7, 1, 2] Rotation of the above array
2 min read