Skip to content

Commit 0547f99

Browse files
authored
Update 143.Reorder-List.cpp
1 parent b32e6f0 commit 0547f99

File tree

1 file changed

+46
-38
lines changed

1 file changed

+46
-38
lines changed

Linked_List/143.Reorder-List/143.Reorder-List.cpp

Lines changed: 46 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -3,57 +3,65 @@
33
* struct ListNode {
44
* int val;
55
* 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) {}
79
* };
810
*/
911
class Solution {
1012
public:
1113
void reorderList(ListNode* head)
1214
{
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)
2221
{
23-
p=p->next;
2422
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;
4024
}
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)
4437
{
45-
if (p!=NULL)
38+
if (p)
4639
{
47-
h->next=p;
48-
h=h->next;
49-
p=p->next;
40+
h->next = p;
41+
p = p->next;
42+
h = h->next;
5043
}
51-
if (q!=NULL)
44+
if (q)
5245
{
53-
h->next=q;
54-
h=h->next;
55-
q=q->next;
46+
h->next = q;
47+
q = q->next;
48+
h = h->next;
5649
}
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;
5866
}
5967
};

0 commit comments

Comments
 (0)