147. Sort a linked list using insertion sort

题目

Sort a linked list using insertion sort.

代码

   public class Solution
    {
        //Definition for singly-linked list.
        public class ListNode
        {
            public int val;
            public ListNode next;
            public ListNode(int x) { val = x; }
        }

        //思路:
        //将待排序的链表节点依次插入到已排序链表的适当位置。
        //定义以下几个变量:
        //1. rtn: 指向已排序链表的头,注意在整个的插入排序过程中它是不变量;
        //2. cur: 指向待排序链表中即将要插入到已排序链表的当前节点;
        //3. pre: 在rtn指向的链表中,cur节点插入位置的前驱,注意pre在每次迭代前始终指向rtn(已排序链表头),迭代过程中要不断向前找到cur插入的位置
        //4. next: 指向待排序链表中即将要插入到已排序链表的下一个节点;
        public ListNode InsertionSortList(ListNode head)
        {
            if (head == null) return null;
            //begining point of the sorted list, set a sentinel
            ListNode rtn = new ListNode(0); 
            ListNode cur = head; //node is inserting
            ListNode pre = rtn; //insert node between pre and pre.next
            while (cur != null)
            {
                ListNode next = cur.next;//save the node that will be inserted.
                //until finding the position meets iter.val <= pre.next.val
                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 = rtn;
                cur = next;
            }
            return rtn.next;
        }
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值