My Solution for Merge Two Sorted Lists


  • 0
    K
    
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null ) return l2;
            if (l2 == null) return l1;
           
            ListNode dummy = new ListNode(0);
            ListNode current = dummy;
            while(l1!=null && l2!=null)
            {
                if(l1.val < l2.val)
                {
                    current.next = l1;
                    l1 = l1.next;
                }
                else{
                    current.next = l2;
                    l2 = l2.next;
                }
                current = current.next;
            }
            if (l1 == null)
                current.next = l2;
            else
                current.next = l1;
            
            // now we also need to free the memory assigned to dummy node
            current = dummy.next;
             dummy = null;  // now since there is nothing that is pointing to the dummy node (0), it will be garbage collected.
            return current;
        }
    }
    
    

Log in to reply
 

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