zoukankan      html  css  js  c++  java
  • 力扣算法题—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 };
  • 相关阅读:
    为什么很多程序员都选择跳槽?
    程序员牛人跳槽
    批处理学习教程
    linux操作命令
    apache配置访问限制
    不常见使用的css
    input中的内容改变时触发的事件
    order by 特殊排序技巧
    CSS设置input placeholder文本的样式
    GoodUI:页面布局的技巧和设计理念
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11768749.html
Copyright © 2011-2022 走看看