1. Simulation: Rotate One Step k Times
Intuition
1. If list length <= 1, return head.
2. Repeat k times:
- Traverse list to find prev (second to last node) and tail (last node).
- prev.next = null.
- tail.next = head.
- head = tail.
3. Return head.
When to apply: Conceptual explanation for small k values.
Algorithm
- Loop k times.
- Traverse to penultimate node.
- Move tail node to the front.
- Update head pointer.
#include <iostream> struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {}}; class Solution {public: ListNode* rotateRight(ListNode* head, int k) { if (!head || !head->next || k == 0) return head; // Calculate length first to reduce k int len = 0; ListNode* curr = head; while (curr) { len++; curr = curr->next; } k %= len; for (int i = 0; i < k; ++i) { ListNode* prev = nullptr; ListNode* tail = head; while (tail->next != nullptr) { prev = tail; tail = tail->next; } prev->next = nullptr; tail->next = head; head = tail; } return head; }}; int main() { ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))); Solution sol; ListNode* res = sol.rotateRight(head, 2); while (res != nullptr) { std::cout << res->val << " "; res = res->next; } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(k * N)— Traverses the list of length N for each of the k rotations, taking O(k * N) time (fails for k = 2 * 109). - Space complexity:
O(1)— Only requires pointer manipulations: O(1) space.