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 Solution: 就是简单的插入算法
1 class Solution { 2 public: 3 ListNode *insertionSortList(ListNode *head) { 4 if (head == nullptr || head->next == nullptr)return head; 5 ListNode *durry, *p, *pre, *cur, *next; 6 durry = new ListNode(-1); 7 durry->next = head; 8 p = pre = cur = next = head; 9 next = cur->next; 10 while (next != nullptr) 11 { 12 cur = next; 13 next = cur->next; 14 p = durry; 15 while (p != cur) 16 { 17 if (p->next->val > cur->val) 18 { 19 pre->next = next; 20 cur->next = p->next; 21 p->next = cur; 22 break; 23 } 24 p = p->next; 25 } 26 if (pre->next == cur)//未移动过 27 pre = cur; 28 } 29 return durry->next; 30 } 31 };
原文地址:https://www.cnblogs.com/zzw1024/p/11768749.html
时间: 2024-11-05 17:17:49