-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path61. Rotate List.cpp
59 lines (46 loc) · 1.05 KB
/
61. Rotate List.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!k)
return head;
int n = 0;
ListNode *onebeforek = head;
ListNode *cur = head;
int kcopy = k;
while(cur && cur->next && k--) {
cur = cur->next;
++n;
}
while(cur && cur->next) {
cur = cur->next;
onebeforek = onebeforek->next;
++n;
}
n++;
if (kcopy > n) {
k = kcopy % n;
k = n - k;
k--;
onebeforek = head;
while(k--) {
onebeforek = onebeforek->next;
}
}
if(kcopy == n)
return head;
if(!cur)
return head;
cur->next = head;
head = onebeforek->next;
onebeforek->next = nullptr;
return head;
}
};