zoukankan      html  css  js  c++  java
  • [leetcode-147-Insertion Sort List]

    Sort a linked list using insertion sort.

    写的思路其实很朴素:

    1.先将原链表一个结点摘下来。

    2.插入到有序的新链表里的合适位置。

    3.循环1、2步骤,直到原链表所有结点遍历完毕。

    时间复杂度为O(n2),空间复杂度为O(1)。

    ListNode* insert(ListNode* head, ListNode* node)
        {//将node插入到有序链表中的合适位置 保持从小到大有序
            ListNode dump(0);
            dump.next = head;        
            ListNode* pre = &dump;
            while (head != NULL && head->val < node->val )
            {
                pre = head;
                head = head->next;            
            }
            pre->next = node;
            node->next = head;
            return dump.next;
        }
        ListNode* insertionSortList(ListNode* head)
        {
            if (head == NULL || head->next == NULL) return head;
            
            ListNode* temp = head;
            ListNode  newList(0) ;        
            while (head != NULL)
            {
                temp = head->next;//保存当前的下一个结点位置
                newList.next =insert(newList.next, head);
                head = temp;        
            }
            return newList.next;
        }
  • 相关阅读:
    ContextMenuStrip 类
    ToolStripMenuItem
    ubuntu16.04下安装cuda8.0
    插入排序
    Python *args **kw
    python面向对象编程
    0/1背包问题(回溯法)
    Python decorator装饰器
    Python 函数式编程
    分治策略(求解递归式的方法)
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6440641.html
Copyright © 2011-2022 走看看