Skip to content

Commit 7a72326

Browse files
committed
refactory the code
1 parent 80be553 commit 7a72326

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed

algorithms/cpp/sortList/sortList.cpp

+8-13
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,7 @@ ListNode *sortList(ListNode *head) {
2828
//find the middle place
2929
ListNode *p1=head, *p2=head->next;
3030

31-
ListNode *prev;
3231
while(p2 && p2->next){
33-
prev = p1;
3432
p1 = p1->next;
3533
p2 = p2->next->next;
3634
}
@@ -44,23 +42,20 @@ ListNode *mergeTwoLists(ListNode* head1, ListNode* head2){
4442
ListNode *p1 = head1, *p2=head2;
4543
static ListNode dummy(0);
4644

47-
dummy.next = p1;
48-
ListNode *prev = &dummy;
45+
ListNode *tail = &dummy;
4946

5047
while(p1 && p2){
5148
if(p1->val < p2->val){
52-
prev = p1;
49+
tail->next = p1;
5350
p1 = p1->next;
5451
}else{
55-
prev->next = p2;
52+
tail->next = p2;
5653
p2 = p2->next;
57-
prev = prev->next;
58-
prev->next = p1;
5954
}
55+
tail = tail->next;
6056
}
61-
if (p2){
62-
prev->next = p2;
63-
}
57+
if (p1) tail->next = p1;
58+
if (p2) tail->next = p2;
6459

6560
return dummy.next;
6661
}
@@ -101,11 +96,11 @@ int main(int argc, char** argv)
10196
for(int i=0; i<n; i++){
10297
a[i] = random()%n + 1;
10398
}
104-
99+
105100
ListNode *p = createList(a, n);
106101
printList(p);
107102
printList(sortList(p));
108-
103+
109104
delete[] a;
110105
return 0;
111106
}

0 commit comments

Comments
 (0)