7ms JAVA Solution


  • 0
    Y
    /**
     * 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) {
            if(head == null)
                return head;
            ListNode pre = new ListNode(0);
            pre.next = head;
            ListNode res = pre;
            while(head.next != null){
                if(head.next.val >= head.val){
                    head = head.next;
                }else{
                    while(pre.next != null){
                        if(pre.next.val > head.next.val){
                            ListNode temp = pre.next;
                            pre.next = head.next;
                            head.next = head.next.next;
                            pre.next.next = temp;
                            break;
                        }else{
                            pre = pre.next;
                        }
                    }
                    pre = res;
                }
            }
            
            return res.next;
        }
    }
    

Log in to reply
 

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