My Not so short Java code beats 96.63%. Easy to understand as well. It can't get better than this I suppose.


  • 2
    P

    There are slight modifications which you can do but that will only make code more complex and hard to understand. In the Interview if you write this kind of easy-to-get-along code, your Interviewer might get happy.

    public ListNode insertionSortList(ListNode head) { //Pretty efficient.
    		if (head == null || head.next == null)
    			return head;
    		ListNode curr = head;
    		ListNode dummy = new ListNode(0);
    		dummy.next = head;
    		ListNode first = dummy;
    
    		while (curr.next != null) {
    			if (curr.val > curr.next.val) { // All messy stuff but make complete sense if you can think.
    				while (first.next.val < curr.next.val) 
    					first = first.next;
    				ListNode node = curr.next; // Some house keeping stuff here.
    				curr.next = node.next;
    				node.next = first.next;
    				first.next = node;
    				first = dummy;
    
    			} else
    				curr = curr.next;
    		}
    
    		return dummy.next;
    

Log in to reply
 

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