LeetCode 147. Insertion Sort List

//利用插入排序的思想对一个链表进行排序
class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head == null || head.next == null) return head;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        //ListNode p1 = dummy.next;
        ListNode p2 = dummy.next;
        ListNode pre2 = dummy;
        while(p2 != null){
            ListNode pre1 = dummy;
            ListNode p1 = dummy.next;
            while(p1 != p2){
                if(p1.val <= p2.val){ //if less than the value, pre1 and p1 keeps moving forward
                    pre1 = p1;
                    p1 = p1.next;
                } else { //
                    pre2.next = p2.next;
                    p2.next = p1;
                    pre1.next = p2;
                    break;
                }
            }
            if(p1 == p2){ //if p1==p2 which means p2 didn't move its position, and so p2 should stay exactly where it is
                pre2 = p2;
                p2 = p2.next;
            } else{ //
                p2 = pre2.next;//reset p2 to pre2.next
            }
        }
        return dummy.next;
    }
}
posted @ 2020-11-20 03:37  EvanMeetTheWorld  阅读(12)  评论(0)    收藏  举报