61. Rotate List
Explanation
To rotate a linked list to the right by k places, we can follow these steps:
- Find the length of the linked list and calculate the actual rotation amount by taking the remainder of k divided by the length.
- Connect the last node to the head node to form a circular linked list.
- Find the new tail node at position length - actual rotation amount - 1 and set the new head node to the next node.
- Break the circular list by setting the new tail node's next to null.
Time complexity: O(n) where n is the number of nodes in the linked list. Space complexity: O(1)
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
int length = 1;
ListNode current = head;
while (current.next != null) {
length++;
current = current.next;
}
int actualRotation = k % length;
if (actualRotation == 0) {
return head;
}
current.next = head; // form a circular linked list
ListNode newTail = head;
for (int i = 0; i < length - actualRotation - 1; i++) {
newTail = newTail.next;
}
ListNode newHead = newTail.next;
newTail.next = null; // break the circular list
return newHead;
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.