147. Insert sort on the linked list (medium)

Ideas:

The insertion sort of the array is from the last traversal from back to front to find the appropriate position to insert, and the linked list cannot be traversed forward, you need a pointer to the leading node, and traverse from the front to the back to find the appropriate position to insert

 

Code:

class Solution {
    public ListNode insertionSortList(ListNode head) {
		//是return head而不是0
		if(head==null) return head;
		//只是一个空链表,不带头节点
		ListNode hair=new ListNode(0);
		hair.next=head;
		
		ListNode lastSorted=head,curr=head.next;
		
		//此处是curr而不是curr.next
		while(curr!=null){
			//是"<="
			if(lastSorted.val<=curr.val){
				lastSorted=lastSorted.next;
				curr=curr.next;
			}else{
				//用到的时候再创建,不要一开始就创建。这样可以减少内存开销
				ListNode prev=hair;
				//是"<="
				while(prev.next.val<=curr.val){
					prev=prev.next;
				}
				lastSorted.next=curr.next;
				curr.next=prev.next;
				prev.next=curr;
				
				//重置,把curr继续放在lastSorted后面,继续遍历
				curr=lastSorted.next;
			}
		}
		return hair.next;
	}
}

break down:

1) Need a pointer hair of the head node , a lastsorted and curr . lastsorted is equivalent to the last element that has been sorted and belongs to the inner loop. curr is the first element that is not sorted and belongs to the outer loop. A prev is used to loop from front to back. It is created when the last element of the inner loop is larger than the first element of the outer loop, which can reduce memory consumption and improve performance

2) If the last element of the inner loop is smaller than the first element of the outer loop, both pointers move backward by one

    if(lastSorted.val<=curr.val){
	lastSorted=lastSorted.next;
	curr=curr.next;
    }

3) Reversing the order code

    ListNode prev=hair;
	//是"<="
	while(prev.next.val<=curr.val){
	    prev=prev.next;
	}
	lastSorted.next=curr.next;
	curr.next=prev.next;
	prev.next=curr;
				
	//重置,把curr继续放在lastSorted后面,继续遍历
	curr=lastSorted.next;

Guess you like

Origin blog.csdn.net/di_ko/article/details/115112041