码迷,mamicode.com
首页 > 编程语言 > 详细

力扣算法题—147Insertion_Sort_List

时间:2019-10-31 00:55:40      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:fir   content   node   while   dia   data   output   class   就是   

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 };

 

力扣算法题—147Insertion_Sort_List

标签:fir   content   node   while   dia   data   output   class   就是   

原文地址:https://www.cnblogs.com/zzw1024/p/11768749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!