zoukankan      html  css  js  c++  java
  • 147. Insertion Sort List

    • Total Accepted: 92484
    • Total Submissions: 288998
    • Difficulty: Medium
    • Contributors: Admin

    Sort a linked list using insertion sort.

    分析



    按照传统的插入方法,对list进行排序 56ms
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    /**
     * 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) {
            ListNode * curi = head, * curj = head;
            ListNode dummy(INT_MIN);
            dummy.next = NULL;
            while(curi != NULL){
                curj = &dummy;
                ListNode * node = curi;
                curi = curi->next;
                while(curj != NULL){
                    if(curj->next == NULL || curj->val<= node->val && curj->next->val > node->val){
                        ListNode * tmp = curj->next;
                        curj->next = node;
                        node->next = tmp;
                        break;
                    }
                    curj = curj->next;
                }
            }
            return dummy.next;
        }
    };

    将list的数值,赋值倒vector<int>中,然后排序结束,再依次赋值回去 19ms
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    /**
     * 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) return head;
            vector<int> list;
            ListNode * h = head;
            while(h != NULL){
                list.push_back(h->val);
                h = h->next;
            }
            sort(list.begin(), list.end());
             
            h = head;
            for(auto val: list){
                h->val = val;
                h = h->next;
            }
            return head;
        }
    };




  • 相关阅读:
    HDU 1016 Prime Ring Problem
    CreateRemoteThread函数多參数传入用法
    Dynamics CRM2015 on-premises直接升级Dynamics CRM2016 on-premises
    cocos2d-x+lua代码热载入(Hot Swap)的研究
    DirectX 9.0c游戏开发手记之“龙书”第二版学习笔记之8: Chap10: Lighting
    js合并table单元格(拼table的时候并不知道详细几行几列)
    简单图模板 Graph
    POJ-3278-Catch That Cow-广搜(BFS)
    android用存到缓存的方法来保存ListView里的数据
    Ubuntu 14.10中连接Win10的smb共享文件
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/dad1866a95b38dcae0414c24f4c185cb.html
Copyright © 2011-2022 走看看