File tree Expand file tree Collapse file tree 1 file changed +46
-38
lines changed
Linked_List/143.Reorder-List Expand file tree Collapse file tree 1 file changed +46
-38
lines changed Original file line number Diff line number Diff line change 3
3
* struct ListNode {
4
4
* int val;
5
5
* ListNode *next;
6
- * ListNode(int x) : val(x), next(NULL) {}
6
+ * ListNode() : val(0), next(nullptr) {}
7
+ * ListNode(int x) : val(x), next(nullptr) {}
8
+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
7
9
* };
8
10
*/
9
11
class Solution {
10
12
public:
11
13
void reorderList (ListNode* head)
12
14
{
13
- if (head==NULL || head->next ==NULL )
14
- return ;
15
-
16
- ListNode* h=new ListNode (0 );
17
- h->next =head;
18
-
19
- ListNode* p=h;
20
- int count=0 ;
21
- while (p->next !=NULL )
15
+ ListNode* dummy = new ListNode (0 );
16
+ dummy->next = head;
17
+
18
+ ListNode* p = dummy;
19
+ int count = 0 ;
20
+ while (p->next )
22
21
{
23
- p=p->next ;
24
22
count++;
25
- }
26
- p=h;
27
- for (int i=0 ; i<(count-count/2 ); i++)
28
- p=p->next ;
29
-
30
- ListNode* temp=p->next ;
31
- p->next =NULL ;
32
- p=temp;
33
- ListNode* q=NULL ;
34
- while (p!=NULL )
35
- {
36
- ListNode* temp=p->next ;
37
- p->next =q;
38
- q=p;
39
- p=temp;
23
+ p = p->next ;
40
24
}
41
-
42
- p=head;
43
- while (p!=NULL || q!=NULL )
25
+
26
+ ListNode* q = dummy;
27
+ for (int i=0 ; i<(count+1 )/2 ; i++)
28
+ q = q->next ;
29
+ ListNode* head2 = q->next ;
30
+ q->next = NULL ;
31
+
32
+ head2 = reverseLinkedList (head2);
33
+
34
+ p = head, q = head2;
35
+ ListNode* h = dummy;
36
+ while (p || q)
44
37
{
45
- if (p!= NULL )
38
+ if (p)
46
39
{
47
- h->next = p;
48
- h=h ->next ;
49
- p=p ->next ;
40
+ h->next = p;
41
+ p = p ->next ;
42
+ h = h ->next ;
50
43
}
51
- if (q!= NULL )
44
+ if (q)
52
45
{
53
- h->next = q;
54
- h=h ->next ;
55
- q=q ->next ;
46
+ h->next = q;
47
+ q = q ->next ;
48
+ h = h ->next ;
56
49
}
57
- }
50
+ }
51
+ }
52
+
53
+ ListNode* reverseLinkedList (ListNode* head)
54
+ {
55
+ ListNode* cur = head;
56
+ ListNode* last = NULL ;
57
+ ListNode* next = NULL ;
58
+ while (cur!=NULL )
59
+ {
60
+ next = cur->next ;
61
+ cur->next = last;
62
+ last = cur;
63
+ cur = next;
64
+ }
65
+ return last;
58
66
}
59
67
};
You can’t perform that action at this time.
0 commit comments