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;
        }
    };
  • 相关阅读:
    关于 flutter_boost splash加载动画
    [BS-23] AFN网络请求上拉/下拉刷新的细节问题总结
    [BS-22] Objective-C中nil、Nil、NULL、NSNull的区别
    [BS-21] 关于OC中对象与指针的思考
    [BS-20] 导航控制器和视图控制器在添加控制器的区别
    ios runtime swizzle
    关于C、OC、C++、OC++、Swift的一些常识
    iOS多线程知识总结--GCD
    使用代码创建AutoLayout约束
    iOS中NSLog输出格式大全
  • 原文地址:https://www.cnblogs.com/CarryPotMan/p/5343689.html
Copyright © 2011-2022 走看看