10(Aug) Rotate a Linked List
10. Rotate a Linked List
The problem can be found at the following link: Question Link
Problem Description
Given the head of a singly linked list, the task is to rotate the linked list clockwise by k nodes, i.e., left-shift the linked list by k nodes, where k is a given positive integer smaller than or equal to the length of the linked list.
Example 1:
Input:
linkedlist: 2->4->7->8->9
k = 3Output:
8->9->2->4->7Explanation:
Rotate 1: 4 -> 7 -> 8 -> 9 -> 2
Rotate 2: 7 -> 8 -> 9 -> 2 -> 4
Rotate 3: 8 -> 9 -> 2 -> 4 -> 7
Example 2:
Input:
linkedlist: 1->2->3->4->5->6->7->8
k = 4Output:
My Approach
Initialization:
Traverse the linked list to find the last node and establish a pointer
pto it.Iterate through the list
ktimes, detaching the first node each time and appending it to the end.
Rotation Logic:
In each rotation, update the head pointer to point to the next node, detach the current head, and attach it to the end by updating
p->next. Updatepto point to the newly added node.
Return:
After performing
krotations, return the new head of the rotated linked list.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n + k), where
nis the number of nodes in the linked list andkis the number of rotations. We traverse the list once to find the tail and performkrotations.Expected Auxiliary Space Complexity: O(1), as we are only using a constant amount of extra space for pointers.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated