Confusion in the second part of question


  • 2
    S

    "The new list should be made by splicing together the nodes of the first two lists."
    What does it mean?

    1. The output list should also be a sorted one.

    2. Output list should be of the form l1 concatenate l2, i.e. all elements of l1 followed by elements of l2.

    3. Neither of these.

    Thanks for any help in advance.


  • 0
    V

    Output list must be sorted. Check with this program .

    public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
        ListNode head = new ListNode(0);
        ListNode fakeHead = head;
    
        int order = -1;
    
        ListNode ptr1 = l1;
        ListNode ptr2 = l2;
    
        if(ptr1 == null) return l2;
        if(ptr2 == null) return l1;
    
        //Tell order
        if(ptr1 != null && ptr1.next != null && ptr1.val != ptr1.next.val) {
            order = ptr1.val - ptr1.next.val;
        } else if(ptr2 != null && ptr2.next != null && ptr2.val != ptr2.next.val) {
            order = ptr2.val - ptr2.next.val;
        }
    
        while(ptr1 != null && ptr2 != null) {
    
            if((ptr1.val - ptr2.val) * order > 0) {
                //ptr1 should be put before ptr2
                head.next = ptr1;
                ptr1 = ptr1.next;
                head = head.next;
                head.next = null;
    
            } else {
                //ptr2 should be put before ptr1
                head.next = ptr2;
                ptr2 = ptr2.next;
                head = head.next;
                head.next = null;
            }
        }
    
        if(ptr1 != null) {
            head.next = ptr1;
        }
    
        if(ptr2 != null) {
            head.next = ptr2;
        }
    
        return fakeHead.next;
    }
    

    }


  • 1
    C

    I think it means that you should not alloc new space for the result list,thus only manipulating the pointers


Log in to reply
 

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