LeetCode--147. Insertion Sort List

题目链接:https://leetcode.com/problems/insertion-sort-list/

要求给单链表进行插入排序,我们先回忆一下数组A的插入排序:索引指针i开始于i=0或1,i之前的表示已经排好顺序的数组,A[i]向前逐个比较,遇到比A[i]大的元素则后移一个,直到遇到一个比A[i]小的元素A[j],则将A[i]放在A[j]后面。那么我们来看看链表,单链表是不能向前移动,只能向后移动,需要一个类似于i的指针dect来限定已经排好序的范围,而需要另一个指针来从头结点开始寻找插入位置,而寻找插入位置相当于从头结点开始寻找第一个比待插入值大的节点的前驱节点,这个前驱节点就是待插入节点的前驱,利用这个前驱才能进行插入操作。

值得注意的是,因为被插入节点的被插入位置可能在头结点之前,所以常用技巧是设置一个虚拟节点。

还有就是如何找到那个被插入节点呢?当然是违反大小顺序的相邻节点的后者需要重新给它安排位置啦。看图说话:

这是原链表:

找到第一个逆序元素的前驱detect,被插入元素为chosen:

从头结点开始寻找第一个比待插入值大的节点的前驱节点:

然后执行插入操作:

重复上述操作:

最终得到一个排好序的链表:

代码如下:

class Solution {
    
    public ListNode insertionSortList(ListNode head) {
        
        if(head==null || head.next==null)
            return head;
        ListNode virtual=new ListNode(Integer.MIN_VALUE);
        virtual.next=head;
        
        ListNode detect=head;
        while(detect.next!=null)
        {
            if(detect.val<=detect.next.val)
                detect=detect.next;
            else
            {
                ListNode chosen=detect.next;
                ListNode pre=virtual;
                while(pre.next.val<chosen.val)
                    pre=pre.next;
                detect.next=chosen.next;
                chosen.next=pre.next;
                pre.next=chosen;
            }
        }
        return virtual.next;
    }
}

效率还是很高的!!!

猜你喜欢

转载自blog.csdn.net/To_be_to_thought/article/details/85056802