Introducing a Fake head


  • 0
    S

    Simple iterative solution by introducing a fake head

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            //Introducing a fake head and appending all the values to it after comparison.
            ListNode head = new ListNode(0);
            ListNode node = head;
            
            while (l1 != null || l2 != null) {
                if (l1 != null && l2 != null) {
                    if (l1.val < l2.val) {
                        node.next = l1;
                        l1 = l1.next;
                    }
                    else {
                        node.next = l2;
                        l2 = l2.next;
                    }
                    node = node.next;
                }
                else if (l1 == null) {
                    node.next = l2;
                    break;
                }
                else if (l2 == null) {
                    node.next = l1;
                    break;
                }
            }
            //Returning the values after the fake head.
            return head.next;
        }
    

Log in to reply
 

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