Very Easy to read, Modular Java code.


  • 0
    K

    Code is pretty self explanatory. The main function is kept simple and the insertion is done in a separate function InsertNode().

    public class Solution {
        public void InsertNode(ListNode dummy, ListNode head){
            ListNode prev = dummy;
            ListNode cur = dummy.next;
            while(cur!=null){
             if(cur.val>head.val){
                break;
             }    
             else{
                 cur = cur.next;
                 prev = prev.next;
             }
            }
            prev.next = head;
            head.next = cur;
        }
        public ListNode insertionSortList(ListNode head) {
            ListNode dummy = new ListNode(0);
            dummy.next = null;
            while(head != null){
                ListNode next = head.next;
                InsertNode(dummy, head);
                head = next;
            }
            return dummy.next;
            
        }
    }
    

Log in to reply
 

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