-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path61_RotateList.cpp
64 lines (58 loc) · 1.29 KB
/
61_RotateList.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
62
63
64
/*
* @Author: [email protected]
* @Last Modified time: 2016-06-28 16:15:41
*/
/**
* 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(head==NULL || head->next==NULL){
return head;
}
// Get the length of the linked list firstly.
int length = 0;
ListNode *len_scan = head;
while(len_scan){
length += 1;
len_scan = len_scan->next;
}
k = k % length;
if(k==0){
return head;
}
// Get the rotated linked list's head.
ListNode *new_tail = head;
for(int i=0; i<length-1-k; i++){
new_tail = new_tail -> next;
}
ListNode *new_head = new_tail->next;
new_tail->next = NULL;
// Go along the linked list to reach the original tail.
ListNode *original_tail = new_head;
while(original_tail and original_tail->next){
original_tail = original_tail->next;
}
// Merge the two parts.
original_tail->next = head;
return new_head;
}
};
/*
[]
0
[1,2,3,4,5]
0
[1,2,3,4,5]
3
[1,2,3,4,5]
9
[]
2
*/