-
Notifications
You must be signed in to change notification settings - Fork 0
/
RotateList.cpp
39 lines (39 loc) · 904 Bytes
/
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
/**
* 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 || k == 0)
return head;
ListNode* first = head, *second = NULL, *third = NULL;
int len = 0;
while(first->next != NULL)
{
len = len + 1;
first = first->next;
}
len = len+1;
if(len == 1)
return head;
if(k >= len)
k = k % len;
if(k == 0)
return head;
third = head;
for(int i = 0; i < len-k-1; i++)
{
head = head->next;
}
second = head;
head = head-> next;
second->next = NULL;
first->next = third;
return head;
}
};