Java solution with explanations.

  • 0

    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){
               = l1;
                        dummy =;
                        l1 =;
                        dummy =;
                        l2 =;
                if(l1 != null && l2 == null){
                if(l1 ==null && l2 != null){
           = l2;

Log in to reply

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