-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path61.rotate-list.cpp
72 lines (69 loc) · 1.34 KB
/
61.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* @lc app=leetcode id=61 lang=cpp
*
* [61] Rotate List
*/
// @lc code=start
/**
* 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)
return head;
int len=0;
ListNode* p=head;
while(p){
p=p->next;
len++;
}
k=k%len;
p=head;
while (len-k>1)
{
p=p->next;
k++;
}
ListNode* l2=p->next;
if(!l2){
return head;
}
auto l3=l2->next;
while (l3&&l3->next)
{
l3=l3->next;
}
p->next=nullptr;
if(!l3)
l2->next=head;
else
l3->next=head;
head=l2;
return head;
*/
if(head==nullptr||head->next==nullptr||k==0)
return head;
auto node =head;
int size=1;
while (node->next)
{
size++;
node=node->next;
}
node->next=head;
k=k%size;
while(--size>=k){
node=node->next;
}
auto l=node->next;
node->next=nullptr;
return l;
}
};
// @lc code=end