147. Insertion Sort List
阿新 • • 發佈:2017-06-03
col link == div sort 選擇 pan 不同 val
題目:
Sort a linked list using insertion sort.
思路:
鏈表的插入排序和數組的插入排序略有不同。以鏈表4->2->3->1->5為例,為方便操作添加一個頭節點-1,此時鏈表為-1->4->2->3->1->5。基本思路為一次選擇前後兩個節點,若後節點大於前節點則不斷向後循環,若後節點小於前節點則取出後節點,並插入到頭節點和前節點之間的位置。
舉例說明:
- 頭節點為-1,cur為節點4,nextnode為節點2。此時,後節點小於前節點,取出節點2,節點3成為新的nextnode。將節點2插入到-1與4之間,此時鏈表為:-1->2->4->3->1->5。
- 頭節點為-1,cur仍然為節點4,nextnode為節點3。此時,後節點小於前節點,取出節點3,節點1成為新的nextnode。將節點3插入到-1與4之間,此時鏈表為:-1->2->3->4->1->5。
- 頭節點為-1,cur仍然為節點4,nextnode為節點1。此時,後節點小於前節點,取出節點1,節點5成為新的nextnode。將節點1插入到-1與4之間,此時鏈表為:-1->1->2->3->4->5。
- 頭節點為-1,cur仍然為節點4,nextnode為節點5。此時,後節點大於前節點,向後循環,nextnode為NULL,排序完成,退出循環。
代碼:
1 class Solution { 2 public: 3 ListNode* insertionSortList(ListNode* head) { 4 if (head == NULL || head->next == NULL) 5 return head; 6 ListNode *newhead = new ListNode(-1); 7 newhead->next = head; 8 ListNode *cur = head; 9 ListNode *nextnode = head->next;10 while (nextnode != NULL) { 11 if (cur->val <= nextnode->val) { 12 nextnode = nextnode->next; 13 cur = cur->next; 14 } else { 15 ListNode *temp = nextnode; 16 cur->next = nextnode->next; 17 nextnode = nextnode->next; 18 19 ListNode *pre = newhead; 20 ListNode *insert = newhead->next; 21 while (insert->val <= temp->val) { 22 pre = insert; 23 insert = insert->next; 24 } 25 pre->next = temp; 26 temp->next = insert; 27 } 28 } 29 return newhead->next; 30 } 31 };
147. Insertion Sort List