-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleet_61.cpp
48 lines (46 loc) · 1005 Bytes
/
leet_61.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
43
44
45
46
47
48
/**
* 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)
return NULL;
int count=0;
ListNode * ptr=head,*final_head,*final_tail=NULL;
while (ptr)
{
count++;
ptr=ptr->next;
}
int left=k % count;
int dont_move=count-left;
if (left==0)
{
return head;
}
ptr=head;
while (dont_move>0)
{
final_tail=ptr;
ptr=ptr->next;
dont_move--;
}
final_head=ptr;
while (ptr->next!=NULL)
{
ptr=ptr->next;
}
if (final_tail !=NULL)
final_tail->next=NULL;
if (count>1)
ptr->next=head;
ptr=final_head;
return final_head;
}
};