Skip to content

Commit 3b3df8c

Browse files
authored
Update 61. Rotate List.cpp
1 parent cd40d74 commit 3b3df8c

File tree

1 file changed

+14
-30
lines changed

1 file changed

+14
-30
lines changed

Linked_List/061.Rotate-List/61. Rotate List.cpp

Lines changed: 14 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -10,38 +10,22 @@ class Solution {
1010
public:
1111
ListNode* rotateRight(ListNode* head, int k)
1212
{
13-
ListNode* pre=new ListNode(0);
14-
pre->next=head;
15-
ListNode* end=pre;
16-
17-
int Len=0;
18-
while (end->next!=NULL)
13+
if (head==0) return NULL;
14+
ListNode* end = head;
15+
int count = 1;
16+
while (end->next != NULL)
1917
{
20-
end=end->next;
21-
Len++;
18+
count++;
19+
end = end->next;
2220
}
23-
24-
if (Len<=1) return head;
21+
int t = count - k % count - 1;
2522

26-
k=k%Len;
27-
if (k==0) return head;
28-
29-
ListNode* p = pre;
30-
ListNode* q = pre;
31-
for (int i=0; i<k; i++)
32-
p=p->next;
33-
34-
while (p->next!=NULL)
35-
{
36-
p=p->next;
37-
q=q->next;
38-
}
39-
40-
ListNode* NewHead=q->next;
41-
q->next=NULL;
42-
end->next=head;
43-
44-
return NewHead;
45-
23+
ListNode* p = head;
24+
for (int i=0; i<t; i++)
25+
p = p->next;
26+
end->next = head;
27+
ListNode* ret = p->next;
28+
p->next = NULL;
29+
return ret;
4630
}
4731
};

0 commit comments

Comments
 (0)