题目:
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
- Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
- At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
- It repeats until no input elements remain.
Example 1:
Input: 4->2->1->3 Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0 Output: -1->0->3->4->5
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* insertionSortList(ListNode* head) { vector<int> nums; ListNode* p = head; while(p){ nums.push_back(p -> val); p = p -> next; } for(int i = 1; i < nums.size(); i++){ int num = nums[i]; int j = i - 1; while(j >= 0 && num < nums[j]){ nums[j+1] = nums[j]; j--; } nums[j+1] = num; } ListNode* newhead = new ListNode(-1); ListNode* t = newhead; for(int i = 0; i < nums.size(); i++){ t -> next = new ListNode(nums[i]); t = t -> next; } t = newhead -> next; delete newhead; return t; } };
if( head == null ){ return head; } ListNode helper = new ListNode(0); //new starter of the sorted list ListNode cur = head; //the node will be inserted ListNode pre = helper; //insert node between pre and pre.next ListNode next = null; //the next node will be inserted //not the end of input list while( cur != null ){ next = cur.next; //find the right place to insert while( pre.next != null && pre.next.val < cur.val ){ pre = pre.next; } //insert between pre and pre.next cur.next = pre.next; pre.next = cur; pre = helper; cur = next; } return helper.next; }