147. Insertion Sort List

Posted markleebyr

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了147. Insertion Sort List相关的知识,希望对你有一定的参考价值。

Sort a linked list using insertion sort.

public class Solution {
    public ListNode insertionSortList(ListNode head) {
 
        ListNode root = new ListNode(0); // 头结点
        root.next = head;
        ListNode p = head;
        ListNode q;
        ListNode r;
//例如6->4->3->7->1->2
        while (p != null && p.next != null) {
            if (p.val <= p.next.val) {//如果此时p等于3,3<7,符合升序,p就指向7
                p = p.next;
            }else { //例如6大于4,则把4和6互换,另q等于4,所以6就指向了3(q.next)
                q = p.next;
                p.next = q.next;
                
                r = root;                                
                while (r.next.val <= q.val) { //此时r.next是6,6大于4,不执行循环
                    r = r.next;//最后进行到0->1->3->4->6->7->2,p等于7,q等于2,则7指向null(q.next),此时1小于2(r.next.val < q.val),所以另r等于1,再往下走,则让2->3, 1->2
                }
 
                q.next = r.next; //使得4指向6
                r.next = q; //root指向4,完成4->6->3
            }
        }
 
        return root.next;
    }
}

以上是关于147. Insertion Sort List的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 147. Insertion Sort List

147. Insertion Sort List

147. Insertion Sort List

[LeetCode] 147. Insertion Sort List

147. Insertion Sort List

147. Insertion Sort List - Medium