首页 > 编程语言 > 详细

链表排序之插入排序

时间:2019-10-28 20:07:41      阅读:80      评论:0      收藏:0      [点我收藏+]

链表排序之插入排序算法:

public static ListNode insertionSortList(ListNode head) {
        if (null == head || null == head.next){
            return head;
        }
        ListNode preHead = new ListNode(-1);
        preHead.next = head;
        ListNode cur = head;
        while (null != cur){
            ListNode pre = preHead;
            ListNode next = cur.next;
            while (null != next && cur.val <= next.val){
                next = next.next;
                cur = cur.next;
            }
            if (null == next){
                break;
            }
            while (pre.next.val <= next.val){
                pre = pre.next;
            }
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }
        return preHead.next;
    }

排序前:6 2 8 4 9 5 1 3 7

排序后:1 2 3 4 5 6 7 8 9

链表排序之插入排序

原文:https://www.cnblogs.com/earthhouge/p/11754606.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!