• [LeetCode]Insertion Sort List


    题目:Insertion Sort List

    对链表进行插入排序。

    注意:

    1.插入头部和插入其他位置需要区分开处理;

    2.可以考虑稳定的排序;

    思路:

    基本的思路就是每次从原链表按顺序取一个节点将它查到已序的新链表的合适的位置。

    ListNode* LeetCode::insertionSortList(ListNode* head){
        if (!head)return head;
        ListNode* root = head;
        head = head->next;//先移动到下一个节点
        root->next = nullptr;//再将根的next置为空
        while (head){
            ListNode* p = root;
            if (head->val < p->val){//当前节点需要插入头部
                root = head;
                head = head->next;
                root->next = p;
            }
            else{
                //找到当前节点head的值小于p的下一个节点的值的p节点
                while (p->next && head->val >= p->next->val){//等于可以保证稳定性
                    p = p->next;
                }
                ListNode* q = head;
                head = head->next;//先移动到下一个节点
                q->next = p->next;//再将当前节点q的next置为p->next
                p->next = q;
            }
        }
        return root;
    }

     还有链表的归并排序:http://www.cnblogs.com/yeqluofwupheng/p/6755973.html

  • 相关阅读:
    SGU 495 Kids and Prizes
    HDU 3853 LOOPS
    HDU 4089 Activation
    HDU 4405 Aeroplane chess
    ZOJ 3329 One Person Game
    POJ 2096 Collecting Bugs
    POJ1573(Robot Motion)
    poj2632(Crashing Robots)
    poj1068(Parencodings)
    poj2506(Tiling)
  • 原文地址:https://www.cnblogs.com/yeqluofwupheng/p/6755568.html
Copyright © 2020-2023  润新知