-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path061_Rotate_List.cpp
More file actions
33 lines (33 loc) · 897 Bytes
/
Copy path061_Rotate_List.cpp
File metadata and controls
33 lines (33 loc) · 897 Bytes
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
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head == NULL || head->next == NULL || k == 0)
return head;
ans = NULL;
ListNode* tmp = head;
int tot = 2;
while(true) {
if((tmp->next)->next == NULL) {
int cnt = 0;
(tmp->next)->next = head;
k = k % tot;
if(k == 0)
k = tot;
dfs(head, tmp->next, head, k, cnt);
break;
}
tmp = tmp->next;
tot++;
}
return ans;
}
private:
ListNode* ans;
void dfs(ListNode* head, ListNode* (&fa), ListNode* (&cur), int k, int &cnt) {
if(cur->next != head)
dfs(head, cur, cur->next, k, cnt);
cnt++;
if(cnt == k)
ans = cur, fa->next = NULL;
}
};