147. Insertion Sort List(对链表进行插入排序)

题目描述

Sort a linked list using insertion sort.
https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif
在这里插入图片描述
在这里插入图片描述

方法思路

创建一个辅助的新链表,并且使用一个指针遍历原链表,每次将原链表中的一个节点插入到新链表的合适位置(即该节点的值大于新链表上的节点的值,又小于后一节点的值)。最后将新链表的头部返回即可。

class Solution {
    //Runtime: 32 ms, faster than 34.04% 
    //Memory Usage: 37.9 MB, less than 54.32% 
    //关键在于创建一个辅助链表
    public ListNode insertionSortList(ListNode head) {
		//边界情况判定
        if( head == null || head.next == null)
			return head;
        
		ListNode helper = new ListNode(0); //新建一个辅助链表
		ListNode cur = head; //the node will be inserted
		ListNode pre = helper; //insert node between pre and pre.next
		ListNode next = null; 
        //the next node will be inserted
		//not the end of input list
		while( cur != null ){
			next = cur.next;
			//find the right place to insert
			while( pre.next != null && pre.next.val < cur.val ){
				pre = pre.next;
			}
			//insert between pre and pre.next
			cur.next = pre.next;//顺序不能乱
			pre.next = cur;
			pre = helper;//每次循环前重置pre为头结点,这样保证每次都从头往后遍历
			cur = next;// cur指针后移一位,进入下一次排序
		}
		
		return helper.next;
	}
}

没有注释的版本:

class Solution{
    public ListNode insertionSortList(ListNode head){
        if( head == null || head.next == null)
			return head;
        ListNode helper = new ListNode(0);
        ListNode pre = helper, cur = head, next = null;
        while(cur != null){
            next = cur.next;
            while(pre.next != null && pre.next.val < cur.val)
                pre = pre.next;
            cur.next = pre.next;
            pre.next = cur;
            pre = helper;
            cur = next;
        }
        return pre.next;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值