Simple Java Solution, 6 ms ,beats 97.01%


  • 0
    Y

    pre is the tail of sorted portion, t is the cursor of the sorted portion, p is the ListNode to be inserted into sorted portion.

    public ListNode insertionSortList(ListNode head) {
        if(head==null)
            return null;
    	ListNode myhead=new ListNode(0);
    	myhead.next=head;
    	ListNode pre=head;
    	ListNode p=null;
    	ListNode t=head;
    	while(pre.next!=null){
    		if(pre.val>pre.next.val){
    			p=pre.next;
    			t=myhead;
    			while(t.next.val<=p.val){
    				t=t.next;
    			}
    			ListNode phou=p.next;
    			p.next=t.next;
    			t.next=p;
    			pre.next=phou;
    		}else{
    			pre=pre.next;
    		}
    	}
    	return myhead.next;
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.