File tree Expand file tree Collapse file tree 1 file changed +14
-30
lines changed
Linked_List/061.Rotate-List Expand file tree Collapse file tree 1 file changed +14
-30
lines changed Original file line number Diff line number Diff line change @@ -10,38 +10,22 @@ class Solution {
10
10
public:
11
11
ListNode* rotateRight (ListNode* head, int k)
12
12
{
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 )
19
17
{
20
- end=end-> next ;
21
- Len++ ;
18
+ count++ ;
19
+ end = end-> next ;
22
20
}
23
-
24
- if (Len<=1 ) return head;
21
+ int t = count - k % count - 1 ;
25
22
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;
46
30
}
47
31
};
You can’t perform that action at this time.
0 commit comments