From 7a7232643b892b2eeca5ca7dd54026e19e1e89e3 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 23 Nov 2015 09:44:35 +0800 Subject: [PATCH] refactory the code --- algorithms/cpp/sortList/sortList.cpp | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/algorithms/cpp/sortList/sortList.cpp b/algorithms/cpp/sortList/sortList.cpp index e07f87298..f73a33ad3 100644 --- a/algorithms/cpp/sortList/sortList.cpp +++ b/algorithms/cpp/sortList/sortList.cpp @@ -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; } @@ -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; } @@ -101,11 +96,11 @@ int main(int argc, char** argv) for(int i=0; i