C# - insert each node into new list


  • 0
        public ListNode InsertionSortList(ListNode head) 
        {
            ListNode newHead = null;
            ListNode curr = head;
            while(curr != null)
            {
                ListNode next = curr.next;
                newHead = Insert(newHead, curr);
                curr = next;
            }
            return newHead;
        }
        
        public ListNode Insert(ListNode head, ListNode node)
        {
            ListNode prev = null;
            ListNode curr = head;
            while (curr != null && curr.val < node.val)
            {
                prev = curr;
                curr = curr.next;
            }
            
            if (prev != null)
            {
                prev.next = node;
                node.next = curr;
                return head;
            }
            else
            {
                node.next = head;
                return node;
            }
        }
    

Log in to reply
 

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