zoukankan      html  css  js  c++  java
  • [LeetCode] Insertion Sort List

    Sort a linked list using insertion sort.

    Hide Tags
     Linked List Sort
     
     
    分析:把链表分成两部分:排好序的和为排序的,排好序的以NULL结尾,cur插在preInsertion和insertion之间,next保存cur->next.
            另外,注意dummy的使用简化了插入头结点的情况。

    时间复杂度O(n^2),空间O(1) 

    /**
     * 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 NULL;
    
                ListNode dummy(INT_MIN);
                dummy.next = head;
    
                ListNode* preInsertion = NULL;
                ListNode* insertion = NULL;
                ListNode* cur = head->next;
                head->next = NULL;//break the sorted and unsorted
                ListNode* next = NULL;
    
                while(cur)
                {   
                    preInsertion = & dummy;
                    insertion = dummy.next;
    
                    //find the right position
                    while(insertion != NULL && cur->val >= insertion->val)
                    {
                        preInsertion = preInsertion->next;
                        insertion = insertion->next;
                    }
    
    #if 0
                    if(insertion == NULL)//cur is max, don't need to move it
                    {
                        next = cur->next;//just store cur first;
                        preInsertion->next = cur; 
                        cur->next = NULL;
                        cur = next;
                    }
                    else
                    {
                        next = cur->next;//just store cur first;
                        preInsertion->next = cur; 
                        cur->next = insertion;
                        cur = next;
                    }
    #endif
                    next = cur->next;//just store cur first;
                    preInsertion->next = cur;
                    cur->next = insertion;
                    cur = next;
    
    
                }
                return dummy.next;
            }
    };
  • 相关阅读:
    JNA 简单示例
    WPF中使用VisiFire制作chart报表
    ActiveMQ CMS 开发环境编译
    c# 程序打包发布
    WPF 程序未处理异常 的捕获
    制作简易浏览器
    C#.NET 支持文件拖放
    C/S代码一例
    Delphi 2010 TStreamReader 和TStreamWriter
    Json数据使用及学习方法
  • 原文地址:https://www.cnblogs.com/diegodu/p/4600224.html
Copyright © 2011-2022 走看看