Java 6ms solution


  • 0
    Z
    public class Solution {
        public ListNode insertionSortList(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode runner = head.next;
            ListNode previous = head;
            while (runner != null) {
                if (runner.val < previous.val) {
                    previous.next = runner.next;
                    ListNode temp = runner;
                    runner = runner.next;
                    ListNode searchNode = head;
                    ListNode previousNode = null;
                    while (searchNode.val < temp.val) {
                        previousNode = searchNode;
                        searchNode = searchNode.next;
                    }
                    if (previousNode == null) {
                        temp.next = head;
                        head = temp;
                    } else {
                        temp.next = searchNode;
                        previousNode.next = temp;
                    }
                } else {
                    previous = runner;
                    runner = runner.next;
                }
            }
            return head;
        }
    }

Log in to reply
 

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