zoukankan      html  css  js  c++  java
  • leetcode:Insertion Sort List

    Sort a linked list using insertion sort.

    分析:此题要求在链表上实现插入排序。

    思路:插入排序是一种O(n^2)复杂度的算法,基本想法就是每次循环找到一个元素在当前排好的结果中相对应的位置然后插进去,经过n次迭代之后就能得到排好序的结果。

    可以这么做:建立一个helper头结点,然后依次将head链表中的结点有序的插入到helper链表中

    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* insertionSortList(ListNode* head) {
            if(head == NULL || head->next == NULL) return head;
            
            ListNode *helper=new ListNode(0);
            ListNode *cur=head;
            ListNode *pre;
            while(cur){
                ListNode *temp=cur->next;
                pre=helper;
                while(pre->next != NULL && pre->next->val < cur->val){
                    pre=pre->next;
                }
                cur->next=pre->next;
                pre->next=cur;
                cur=temp;
            }
            return helper->next;
        }
    };
    

      

  • 相关阅读:
    maven配置
    redis测试
    智慧社区技术总结
    视频导航
    Delphi 任务栏中不显示窗口
    Delphi 设置程序图标为系统默认图标
    清除Windows系统图标缓存
    C/C++ 变量的本质分析
    005 C/C++ 数据类型_void
    004 C/C++ 数据类型_类型别名
  • 原文地址:https://www.cnblogs.com/carsonzhu/p/5205438.html
Copyright © 2011-2022 走看看