From ed90b1bdc0017481bd48cc31728f7bd6e9bfc3f0 Mon Sep 17 00:00:00 2001 From: Jia Xu Date: Fri, 19 Dec 2014 21:14:24 -0800 Subject: [PATCH] Correct solution for Insertion Sort List Modify the code to pass the test of cases such as 1-> NULL or 1->1->NULL The code has passed the test cases in leetcode --- C++/chapSorting.tex | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/C++/chapSorting.tex b/C++/chapSorting.tex index a1192eb5..9c1edc51 100644 --- a/C++/chapSorting.tex +++ b/C++/chapSorting.tex @@ -157,23 +157,28 @@ \subsubsection{代码} public: ListNode *insertionSortList(ListNode *head) { ListNode dummy(INT_MIN); - //dummy.next = head; - - for (ListNode *cur = head; cur != nullptr;) { - auto pos = findInsertPos(&dummy, cur->val); - ListNode *tmp = cur->next; - cur->next = pos->next; - pos->next = cur; - cur = tmp; - } + dummy.next = head; + + for (ListNode *p = &dummy; p->next != nullptr;) { + auto pos = findInsertPos(&dummy, p->next, p->next->val); + if(pos->next == p->next){ + p = p->next; + }else{ + ListNode *tmp = p->next->next; + p->next->next = pos->next; + pos->next = p->next; + p->next = tmp; + } + } return dummy.next; } - ListNode* findInsertPos(ListNode *head, int x) { + ListNode* findInsertPos(ListNode *head, ListNode *last, int x) { ListNode *pre = nullptr; - for (ListNode *cur = head; cur != nullptr && cur->val <= x; - pre = cur, cur = cur->next) - ; + + for (ListNode *cur = head; cur != last && cur->val <= x; cur = cur->next) + pre = cur; + return pre; } };