Java Solution, easy understand, beat 88%


  • 0
    A
    public class Solution {
        public ListNode insertionSortList(ListNode head) {
            if (head ==null) return head;
            ListNode sorted = head;
            ListNode cur;
            ListNode prev = head;
            while(sorted.next!=null){
                cur = sorted.next;
                if(cur.val<sorted.val) {
                    if(head.val>cur.val){
                        sorted.next=cur.next;
                        cur.next = head;
                        head = cur;
                    } else {
                        prev = head;
                        while(prev.next.val<=cur.val){
                            prev = prev.next;
                        }
                        sorted.next = cur.next;
                        cur.next = prev.next;
                        prev.next = cur;
                    }
                }else sorted = sorted.next;   
            }
            return head;
        }
    }

Log in to reply
 

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