-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotate List.cpp
50 lines (41 loc) · 1010 Bytes
/
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
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL)
return head;
int n = 1;
ListNode *p = head;
while (p->next != NULL) {
p = p->next;
n++;
}
if (n == 1) {
return head;
}
k = k % n;
if (k == 0) {
return head;
}
ListNode *tail = p;
p = head;
for (int i = 0; i < n - k - 1; i++) {
p = p->next;
}
//split from p
ListNode *tmp = p->next;
tail->next = head;
head = tmp;
p->next = NULL;
return head;
}
};