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

    Sort a linked list using insertion sort.

    解法:

    Well, life gets difficult pretty soon whenever the same operation on array is transferred to linked list.

    First, a quick recap of insertion sort:

    Start from the second element (simply a[1] in array and the annoying head -> next -> val in linked list), each time when we see a node with val smaller than its previous node, we scan from the head and find the position that the current node should be inserted. Since a node may be inserted before head, we create a new_head that points to head. The insertion operation, however, is a little easier for linked list.

    Now comes the code:

    /**
     * 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||!head->next) return head;
            ListNode* new_head ;
            new_head->next = head;
            ListNode* pre = new_head;
            ListNode* cur = head;
            while(cur) {
                if(cur->next && cur->next->val < cur->val) {
                    while(pre->next && pre->next->val < cur->next->val) pre = pre->next;
                    ListNode* temp = pre->next;
                    pre->next = cur->next;
                    cur->next = cur->next->next;
                    pre->next->next = temp;
                    pre = new_head;
                }
                else cur = cur->next;
            }
            return new_head->next;
        }
    };

    方法二:

    class Solution {
    public:
        /**
         * @param head: The first node of linked list.
         * @return: The head of linked list.
         */
        ListNode *insertionSortList(ListNode *head) {
            ListNode *dummy = new ListNode(0);
            // 这个dummy的作用是,把head开头的链表一个个的插入到dummy开头的链表里
            // 所以这里不需要dummy->next = head;
    
            while (head != NULL) {
                ListNode *temp = dummy;
                ListNode *next = head->next;
                while (temp->next != NULL && temp->next->val < head->val) {
                    temp = temp->next;
                }
                head->next = temp->next;
                temp->next = head;
                head = next;
            }
    
            return dummy->next;
        }
    };
  • 相关阅读:
    Build-in Function:abs(),all(),any(),assii(),bin(),issubclass(),bytearray(),isinstance()
    函数及while实例
    提示'HTTP消息不可读'
    python中关于不执行if __name__ == '__main__':测试模块的解决
    python输出测试报告测试成功
    SqlServer——批量插入数据
    网页样式——各种炫酷效果持续更新ing...
    网站部署发布到互联网等整套流程
    如何远程操控别人的电脑?我来教你
    代码生成工具——CodeSmith
  • 原文地址:https://www.cnblogs.com/CarryPotMan/p/5343689.html
Copyright © 2011-2022 走看看