LeetCode刷题笔记 147. 对链表进行插入排序

147. 对链表进行插入排序

题目要求

147. 对链表进行插入排序

题解

https://github.com/soulmachine/leetcode

class Solution {
public:
    ListNode* findInsertPos(ListNode *head,int x){
        ListNode *pre=nullptr;
        for(ListNode *cur=head;cur&&cur->val<=x;pre=cur,cur=cur->next) 
        ;
        return pre;
    }
    ListNode* insertionSortList(ListNode* head) {
        ListNode dummy(INT_MIN);
        //dummy.next=head;  是的,这次真的没有这一句

        for(ListNode *cur=head;cur;){
            auto pos=findInsertPos(&dummy,cur->val);
            ListNode *tmp=cur->next;
            cur->next=pos->next;
            pos->next=cur;
            cur=tmp;
        }
        return dummy.next;
    }
};

思路总结:

  • findInsertPos()返回的是第一个大于cur->val的节点的前一个节点的指针,如
    当cur->val为3,dummy链表为[INT_MIN,1,2,4]时,返回的是指向2的指针即[2,4]
  • 插入流程:
    1. 将cur位置的下一个节点保存在tmp中
    2. 待插入位置的下一个节点链接到cur节点的后面
    3. cur节点链接到插入位置的前一个节点的后面
    4. 把cur的指针指向tmp,即这一轮cur的下一个节点
发布了18 篇原创文章 · 获赞 0 · 访问量 1796

猜你喜欢

转载自blog.csdn.net/g534441921/article/details/104160317