[LeetCode] Insertion Sort List

前言

Insertion Sort List算是Linked List tag下的一道中等难度的题吧,可以用来复习链表的选择排序操作。解法很固定,没什么讨论的余地。

题目

https://leetcode.com/problems/insertion-sort-list/
Sort a linked list using insertion sort.
排序一个链表,指定必须采用插入排序算法。

分析

插入排序是比较基础的一种排序算法,遍历元素,把它插入到该插入的位置,这里有一个网页动画可以帮助理解这个算法的具体过程。(同时也提供了其他一些常见的排序算法的可视化图形表示)
这里需要注意的是,为了避免处理一些比较繁琐的边界条件问题,我们使用一个Dummy Head节点来作为表头节点。代码写的比较清楚,直接show code.

代码

class Solution { 
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode* Dummy = new ListNode(0);
        Dummy -> next = head;
        ListNode* pre = Dummy;
        ListNode* cur = Dummy->next;// which is just head
        while (cur) {// cur != NULL
            if (cur -> next && cur -> next -> val < cur -> val) {
                while (pre -> next && pre -> next -> val < cur -> next -> val)
                    pre = pre -> next;
                //Now we get where to insert. Insert cur -> next after pre.
                ListNode* tmp = pre -> next;
                pre -> next = cur -> next;
                cur -> next = cur -> next -> next;
                pre -> next -> next = tmp;
                /* Move pre back to Dummy. */
                pre = Dummy;
            }
            else cur = cur -> next;
        }
        return Dummy->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值