-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotate_list.cpp
More file actions
45 lines (41 loc) · 1 KB
/
Copy pathrotate_list.cpp
File metadata and controls
45 lines (41 loc) · 1 KB
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head: the list
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode *rotateRight(ListNode *head, int k) {
// write your code here
if (head == NULL || head->next == NULL) {
return head;
}
ListNode dummy(0);
dummy.next = head;
ListNode* fast = &dummy;
ListNode* slow = &dummy;
while (k > 0) {
fast = fast->next;
if (fast == NULL) {
fast = head;
}
k--;
}
while (fast->next != NULL) {
fast = fast->next;
slow = slow->next;
}
ListNode* temp = slow->next;
slow->next = NULL;
fast->next = head;
return temp;
}
};