• [LeetCode]85. Insertion Sort List链表插入排序


    Sort a linked list using insertion sort.

    Subscribe to see which companies asked this question

    解法:设置3个指针:应插入位置的前一个节点first、当前处理节点third和其前一个节点second,设置辅助节点help指向头节点。然后从头节点的next节点开始遍历,一个个插入正确位置即可。注意在插入到新位置之前需要链接好second和third->next,防止链表断开。

    /**
     * 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 || head->next == NULL) return head;
            ListNode* help = new ListNode(0);
            help->next = head;
            ListNode *second = head, *third = head->next;
            while (third != NULL) {
                ListNode* first = help;
                if (third->val < second->val) {
                    while (first->next->val <= third->val) // 找到插入点
                        first = first->next;
                    second->next = third->next; // 链接断开点
                    third->next = first->next; // 插入到新的位置
                    first->next = third;
                    third = second->next; // 前移一个节点
                }
                else { // 前移一个节点
                    second = third;
                    third = third->next;
                }
            }
            return help->next;
        }
    };
  • 相关阅读:
    修改程序堆栈的可执行属性
    【转】关于C语言生成不重复的随机数
    Apriori算法
    远程连接服务器端Jupyter Notebook
    Android KeyLogger Demo
    Windows消息钩取
    基址重定位表&.reloc节区
    调试UPX压缩的notepad
    PE文件格式
    apk逆向
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4968474.html
Copyright © 2020-2023  润新知