Java solution with explanations.


  • 0
    L

    This problem is similar to the 2nd Add two numbers.
    There may be a lot of more fancy methods. My instinct thought is
    loop though all the lists till reach a null.

    The similarity between the two problems is not sure about the length of two linkedlists.
    I did the while loop. The procedure is pretty straight forward. Hope it will help you.

    There is nothing special purpose to use the dummy point. For me, dummy points are used to
    avoid the case the the first node of a list is deleted.

    Correct me if i am wrong. Thx!!!

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode dummy = new ListNode(0);
            ListNode head = dummy;
            
            while(l1!= null || l2!= null){
                if(l1 != null && l2 != null){
                    if(l1.val <= l2.val){
                        dummy.next = l1;
                        dummy = dummy.next;
                        l1 = l1.next;
                    }else{
                        dummy.next =l2;
                        dummy = dummy.next;
                        l2 = l2.next;
                    }
                }
                if(l1 != null && l2 == null){
                    dummy.next= l1;
                    break;
                }
                if(l1 ==null && l2 != null){
                    dummy.next = l2;
                    break;
                }
            }
            return head.next;
        }
    }
    

Log in to reply
 

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