LeetCode 147. Insertion Sort List

问题描述

  • Sort a linked list using insertion sort.
  • 地址

问题分析

  • 该题是在链表上实现插入排序。
  • 具体做法为,新建一个空链表,然后从原链表中每次取出一个节点,然后从前到后遍历新链表,找到待插入的位置,将该节点插入到新链表中。 注意,与反转部分链表的不同,这个是取出一个节点!!!

代码实现

     public ListNode insertionSortList(ListNode head) {
         if (head == null || head.next == null) {
             return head;
         }
         //新链表的头结点
         ListNode dummy = new ListNode(0);
         //待插入节点
         ListNode insertNode = head;
         //下一个待插入节点
         ListNode nextInsert = null;
         //用于寻找待插入位置
         ListNode curNode = dummy;
         while (insertNode != null) {
             //临时保存原链表中的下一个待插入位置
             nextInsert = insertNode.next;
             //从头到尾,在新链表中查找insertNode待插入的位置
             curNode = dummy;
             while (curNode.next != null && curNode.next.val < insertNode.val) {
                 curNode = curNode.next;
             }
             //将insertNode 插入到 curNode 与 curNode.next 之间
            insertNode.next = curNode.next;
            curNode.next = insertNode;
            insertNode = nextInsert;
         }
         return dummy.next;
     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值