forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotate_List.cpp
39 lines (35 loc) · 875 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
/**
* 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 or k < 1) return head;
int len = 0;
ListNode *iter = head, *tail = head;
while(iter) {
len++;
tail = iter;
iter = iter->next;
}
iter = head;
k %= len;
if(k == 0) return head;
int cutPoint = len - k;
int i = 0;
while(i < cutPoint - 1) {
++i;
iter = iter->next;
}
ListNode *newHead = iter->next;
iter->next = NULL;
tail->next = head;
head = newHead;
return head;
}
};