Skip to content

Commit f78cad2

Browse files
committed
Create Rotate List.cpp
1 parent 4465054 commit f78cad2

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Rotate List.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode *rotateRight(ListNode *head, int k) {
12+
// Start typing your C/C++ solution below
13+
// DO NOT write int main() function
14+
ListNode *ptr=head,*pre;
15+
int len=0;
16+
while (ptr)
17+
{
18+
++len;
19+
ptr=ptr->next;
20+
}
21+
if (!len)return head;
22+
k%=len;
23+
if (!k)return head;
24+
int c=len-k;
25+
pre=ptr=head;
26+
while (c--)
27+
{
28+
pre=ptr;
29+
ptr=ptr->next;
30+
}
31+
pre->next=NULL;
32+
ListNode *ed=ptr;
33+
while (ed)
34+
{
35+
pre=ed;
36+
ed=ed->next;
37+
}
38+
pre->next=head;
39+
return ptr;
40+
}
41+
};

0 commit comments

Comments
 (0)