Skip to content

Commit

Permalink
refactory the code
Browse files Browse the repository at this point in the history
  • Loading branch information
haoel committed Nov 23, 2015
1 parent 80be553 commit 7a72326
Showing 1 changed file with 8 additions and 13 deletions.
21 changes: 8 additions & 13 deletions algorithms/cpp/sortList/sortList.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ ListNode *sortList(ListNode *head) {
//find the middle place
ListNode *p1=head, *p2=head->next;

ListNode *prev;
while(p2 && p2->next){
prev = p1;
p1 = p1->next;
p2 = p2->next->next;
}
Expand All @@ -44,23 +42,20 @@ ListNode *mergeTwoLists(ListNode* head1, ListNode* head2){
ListNode *p1 = head1, *p2=head2;
static ListNode dummy(0);

dummy.next = p1;
ListNode *prev = &dummy;
ListNode *tail = &dummy;

while(p1 && p2){
if(p1->val < p2->val){
prev = p1;
tail->next = p1;
p1 = p1->next;
}else{
prev->next = p2;
tail->next = p2;
p2 = p2->next;
prev = prev->next;
prev->next = p1;
}
tail = tail->next;
}
if (p2){
prev->next = p2;
}
if (p1) tail->next = p1;
if (p2) tail->next = p2;

return dummy.next;
}
Expand Down Expand Up @@ -101,11 +96,11 @@ int main(int argc, char** argv)
for(int i=0; i<n; i++){
a[i] = random()%n + 1;
}

ListNode *p = createList(a, n);
printList(p);
printList(sortList(p));

delete[] a;
return 0;
}

0 comments on commit 7a72326

Please sign in to comment.