Leetcode: Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // Start typing your Java solution below
        // DO NOT write main() function
        //a fake head
        //we should return head.next at the end
        ListNode head = new ListNode(0);
        ListNode newRunner = head;
        ListNode runner1 = l1;
        ListNode runner2 = l2;

        while(runner1!=null && runner2!=null){
            if(runner1.val<=runner2.val){
                newRunner.next = runner1;
                runner1 = runner1.next;
            }else{
                newRunner.next = runner2;
                runner2 = runner2.next;
            }
            newRunner = newRunner.next;
        }

        newRunner.next = runner1==null?runner2:runner1;
        return head.next;

    }
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *