leetcode 147. Insertion Sort List

链表插入排序。维护三个节点。当前节点cur,下一个节点post,节点node表示其插入位置,在其之后。每次取出cur,插入链表,从头比较。注意和node.next比较,这样就能少维护一个pre节点,通过node就能拿到node.next节点。

注意,插入链表的链表断开,否则会死循环

public ListNode insertionSortList(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode cur=head.next,post=cur.next;
        head.next=null; //要插入的链表断开,否则会死循环
        while(cur!=null){
            post=cur.next;
            ListNode node=head;
            if(node.val>cur.val){//最前面的边界情况
                cur.next=node;
                head=cur;
            }else{
                while(node.next!=null&&node.next.val<cur.val){//用next节点判断可以少记录一个pre节点
                    node=node.next;//cur插到node后面           //node是前一个节点,容易拿到node.next
                }
                cur.next=node.next;
                node.next=cur;
            }
            cur=post;
        }
        return head;
    }


猜你喜欢

转载自blog.csdn.net/yaoct/article/details/80412608