-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
61 lines (53 loc) · 1.39 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <algorithm>
#include <array>
#include <climits>
#include <functional>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
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) {}
};
using namespace std;
class Solution {
private:
int countNodes(ListNode* head, int length) {
if (!head) {
return length;
}
return countNodes(head->next, length + 1);
}
public:
ListNode* rotateRight(ListNode* head, int k) {
// k can be more than the length of the list, in that case, it will
// circle back.
int size = countNodes(head, 0);
if (!head || !head->next || k == 0 || k % size == 0) {
return head;
}
k = k % size;
ListNode* newTail = head;
// size - k represents the kth node from the back. Iterate 1 less to get
// the newTail node
for (int i = 0; i < size - k - 1; ++i) {
newTail = newTail->next;
}
// The newHead of the list will be the next node.
ListNode* newHead = newTail->next;
ListNode* remaining = newHead; // nodes after the newHead
while (remaining->next) {
remaining = remaining->next;
}
remaining->next = head;
newTail->next = nullptr;
return newHead;
}
};