zoukankan      html  css  js  c++  java
  • LeetCode OJ-- Insertion Sort List **

    https://oj.leetcode.com/problems/insertion-sort-list/

    链表实现插入排序

    首先插入排序是指:

    a b c d e g m 对b也就是第二个位置选做元素num开始遍历n-1次

    对每个num,找到从第0个位置开始,它应该待的位置,把它插入进去。

    对于链表来说,首先new一个 dummy 节点,这样比较方便对 head的操作 dummy->next = head。

    然后从head->next为第二个元素,也就是从它开始遍历处理

    每一次处理中从 dummy->next作为开始,因为 head 可能已经换位置了.

    记录当前处理的位置的上一个位置,这样如果需要把这个点插入到前面,也就是从这个位置删除的话,就 before->next = num->next相当于删除了。

    同时为了插入,即在合适的位置插入,需要记录要插入的上一个位置 num->next = pointer, before_should->next = num,相当于插入了。

     1 struct ListNode {
     2       int val;
     3       ListNode *next;
     4       ListNode(int x) : val(x), next(NULL) {}
     5   };
     6  
     7 class Solution {
     8 public:
     9     ListNode *insertionSortList(ListNode *head) {
    10         if(head == NULL)
    11             return NULL;
    12         
    13 
    14         ListNode *dummy = new ListNode(-1);
    15         dummy->next = head;
    16         ListNode *before = head;
    17         ListNode *before_bigger = dummy;
    18 
    19         for(ListNode *num = head->next; num!=NULL; num = num->next)
    20         {
    21             ListNode *point = NULL;
    22             bool flag = false;
    23             before_bigger = dummy;
    24             for(point = dummy->next; point!= num; point=point->next)
    25             {
    26                 if(point->val > num->val)
    27                 {
    28                     flag = true;
    29                     break;
    30                 }
    31                 before_bigger = before_bigger->next;
    32             }
    33 
    34             //need insert
    35             if(flag)
    36             {
    37                 before->next = num->next;
    38                 before_bigger->next = num;
    39                 num->next = point;
    40                 num = before;
    41             }
    42             else 
    43             {
    44                 before = before->next;
    45             }
    46         }
    47         return dummy->next;
    48     }
    49 };
  • 相关阅读:
    CCF NOI1121 逆波兰表达式
    Vijos P1217 乒乓球【模拟+输入输出】
    Vijos P1304 回文数【回文+进制】
    NUC1041 数字三角形【DP】
    CCF NOI1070 汉诺塔游戏
    CCF NOI1069 分解因数
    CCF NOI1149 N皇后问题
    CCF NOI1153 素数环
    CCF NOI1170 质因数分解
    POJ NOI MATH-7832 最接近的分数
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3818599.html
Copyright © 2011-2022 走看看