Reference Java solution with creating a totally new list


  • 0
    S

    I am wondering what the problem description "return it as a new list" mean. If it means we should return a totally new list without changing the structure of l1 and l2, then most of the excellent solutions posted on this forum will not meet the requirement. Here is my code with creating a total new list. The idea is same, difference is just to create new notes.

     public class Solution {
            public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
                ListNode dummy = new ListNode(0);
                ListNode p = dummy;
                
                while (l1 != null && l2 !=null)
                {
                    if (l1.val < l2.val)
                    {
                        ListNode a = new ListNode(l1.val);
                        p.next = a;
                        p = p.next;
                        l1 = l1.next;
                    }
                    else
                    {
                        ListNode a = new ListNode(l2.val);
                        p.next = a;
                        p = p.next;
                        l2 = l2.next;
                    }
                }
                if (l1 == null)
                {
                    while (l2 != null)
                    {
                        ListNode a = new ListNode(l2.val);
                        p.next = a;
                        p = p.next;
                        l2 = l2.next;
                    }
                }
                else
                {
                    while (l1 != null)
                    {
                        ListNode a = new ListNode(l1.val);
                        p.next = a;
                        p = p.next;
                        l1 = l1.next;
                    }
                }
                return dummy.next;
            }
        }

Log in to reply
 

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