My accepted Java solution


  • 0
    R

    public class Solution {
    public ListNode insertionSortList(ListNode head) {

        if(head == null)
          return null;
    
        ListNode p1 = head;
        ListNode p2 = head.next;
        ListNode p2_pre = head;
        ListNode temp2;
        
        while (p2 != null) {
          p1 = head;
          if(p2.val < p1.val) {   
            temp2 = p2.next;		  
    	    head = p2;
    		p2_pre.next = p2.next;
    		p2.next = p1;
    		p2 = temp2;		  
          }
          else {
            while (p1.next.val < p2.val) {
              p1 = p1.next;          
            }
    		if (p1.next != p2) {
              temp2 = p2.next;		
    		  p2_pre.next = p2.next;
    		  p2.next = p1.next;
    		  p1.next = p2;
    		  p2 = temp2;
    		}
    		else {
    		  p2_pre = p2;
    		  p2 = p2.next;
    		}
          }   
        }        
        return head;
    }
    

    }


Log in to reply
 

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