My AC Java solution


  • 1
    H
    public class Solution {
    public ListNode insertionSortList(ListNode head) {
    	if (head == null || head.next == null) {
    		return head;
    	}
    	ListNode fhead = new ListNode(Integer.MIN_VALUE); 
        fhead.next = head;
    	ListNode last = head;
    
    	while (last != null){
    	    ListNode pre = last;
    	    head = fhead;
    	    last = last.next;
    		while (head.next != last && last != null) {
    			if (head.next.val > last.val) {
    				ListNode temp = new ListNode(last.val);
    				temp.next = head.next;
    				head.next = temp;
    				if (last.next != null) {
    					last.val = last.next.val;
    					last.next = last.next.next;
    					last = pre;
    				} else{
    					pre.next = null;
    				}
                    break;					
    			} else head = head.next;
    		}
    		if (head.next == last && head.val > last.val) {
    		    int temp = head.val;
    		    head.val = last.val;
    		    last.val = temp;
    		}
    
    	}
    	return head.next;
    }
    }

Log in to reply
 

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