力扣算法题—147Insertion_Sort_List

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:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. 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.
  3. 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 };

 

posted @ 2019-10-30 23:29  自由之翼Az  阅读(191)  评论(0编辑  收藏  举报