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){
                newRunner.next = runner1;
                runner1 = runner1.next;
                newRunner.next = runner2;
                runner2 = runner2.next;
            newRunner = newRunner.next;

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


Leave a Reply

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