LeetCode 147. 对链表进行插入排序

题目链接

147. 对链表进行插入排序

思路分析

这个题,就是插入排序的链表版。做的时候要注意保存当前结点的下结点以及及时断开next指针即可。

代码实现

class Solution {
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = head;
        while(cur != null){
            ListNode nxt = cur.next;
            cur.next = null;
            ListNode temp = dummy;
            while(temp.next != null && temp.next.val < cur.val){
                temp = temp.next;
            }
            ListNode nxt2 = temp.next;
            temp.next = cur;
            cur.next = nxt2;
            cur = nxt;
        }
        return dummy.next;
    }
}

总结

这个题还有优化的空间,因为如果我们链表原来就是相对有序的话,根本不需要那么多次的比较。但是我比较菜,第一时间只想到了上面的方法- -

原文地址:https://www.cnblogs.com/ZJPaang/p/14009241.html