Share My Clean Solution


  • 0
    C
    public class Solution {
      public ListNode insertionSortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode node = head.next;
        head.next = null;
        while (node != null) {
            ListNode temp = node.next;
            node.next = null;
            insert(pre, node);
            node = temp;
        }
        return pre.next;
      }
      
      // Insert the node into sorted list
      public void insert(ListNode pre, ListNode node) {
        ListNode nodeBeforeInsertPosition = pre;
        while (nodeBeforeInsertPosition.next != null && nodeBeforeInsertPosition.next.val < node.val) {
            nodeBeforeInsertPosition = nodeBeforeInsertPosition.next;
        }
        node.next = nodeBeforeInsertPosition.next;
        nodeBeforeInsertPosition.next = node;
      }
    

    }


Log in to reply
 

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