0
点赞
收藏
分享

微信扫一扫

0链表中等 LeetCode147. 对链表进行插入排序

jjt二向箔 2022-01-09 阅读 81

147. 对链表进行插入排序

描述

对链表进行插入排序。

分析

将链表看成两部分,一半是已经排好序的,一半是未排序的。
把排好序的最后一个节点的后继看作待排序的结点,这很重要,能够确保遍历的终止。

class Solution {
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = head;
        while(cur != null && cur.next != null){
            if(cur.val <= cur.next.val){
                cur = cur.next;
                continue;
            }
            ListNode pre = dummy;
            ListNode target = cur.next;
            //已排好序的结点里一定存在一个节点大于cur.next
            while(pre.next.val < cur.next.val){
                pre = pre.next;
            }
            ListNode tmpc = cur.next.next;
            ListNode tmpp = pre.next;
            pre.next = target;
            target.next = tmpp;
            cur.next = tmpc;
        }
        return dummy.next;
    }
}
举报

相关推荐

0 条评论