Concise 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 || head.next==null) return head;
            ListNode dummyhead=new ListNode(0);
            ListNode pre=dummyhead;
            while (head!= null){
                ListNode current=head;
                head=head.next;
                pre=dummyhead;
                while (pre.next!=null && pre.next.val<current.val){
                    pre=pre.next;
                }
                current.next=pre.next;
                pre.next=current;
                
            }
            return dummyhead.next;
        }
    }
    

Log in to reply
 

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