-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotate_List.cpp
42 lines (38 loc) · 948 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
/**
* 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 || k == 0)
return head;
/* Get the length of the list */
int size = 0;
ListNode *cur = head;
do {
++size;
cur = cur->next;
} while (cur);
k %= size;
/* Rotate the list */
int cur_index = 0, new_head_prev = size - k - 1;
cur = head;
while (cur_index < new_head_prev) {
cur = cur->next;
++cur_index;
}
ListNode *prev = cur;
while(cur->next) {
cur = cur->next;
}
cur->next = head;
head = prev->next;
prev->next = NULL;
return head;
}
};