Share my java solution


  • 0
    M

    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public ListNode insertionSortList(ListNode head) {
      ListNode dummy = new ListNode(-1);
      ListNode target = dummy;
      while(head!=null){

           if(target.next==null || target.next.val >= head.val){
               ListNode temp = target.next;
               //swap
               target.next = head;
               head = head.next;
               target.next.next = temp;
               
                // start from the head
               target = dummy;
           }else{
               
               target = target.next;
           }
       }
       
       return dummy.next;
      

      }
      }


Log in to reply
 

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