-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathRotate List.cpp
41 lines (41 loc) · 899 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
40
41
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *ptr=head,*pre;
int len=0;
while (ptr)
{
++len;
ptr=ptr->next;
}
if (!len)return head;//forgot to judge oringinal list is NULL
k%=len;
if (!k)return head;
int c=len-k;
pre=ptr=head;
while (c--)
{
pre=ptr;
ptr=ptr->next;
}
pre->next=NULL;
ListNode *ed=ptr;
while (ed)
{
pre=ed;
ed=ed->next;
}
pre->next=head;
return ptr;
}
};