joshita / dev

Published

- 1 min read

Merge two sorted linked list

img of Merge two sorted linked list

Merge Two Sorted Lists You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.

TotalValue

   private Node mergeTwoSortedLL(Node l1, Node l2) {
        Node head = new Node(-1, null);

        Node newList = head;
        while (l1 != null && l2 != null) {
            if(l1.val <= l2.val) {
                newList.next = l1;
                l1 = l1.next;
             } else {
                newList.next = l2;
                 l2 = l2.next;
             }
            newList = newList.next;
        }
        newList.next = l1 == null ? l1 : l2; //optimized 
        // only either of them would be exhaused, either of the list woulf be null in the condition
        return head.next;
    }