Interview Question: Merge two sorted singly linked lists without creating new nodes

后端 未结 26 3003
有刺的猬
有刺的猬 2020-12-02 04:09

This is a programming question asked during a written test for an interview. \"You have two singly linked lists that are already sorted, you have to merge them and return a

26条回答
  •  清歌不尽
    2020-12-02 04:23

    My take on the question is as below:

    Pseudocode:

    Compare the two heads A and B. 
    If A <= B, then add A and move the head of A to the next node. 
    Similarly, if B < A, then add B and move the head of B to the next node B.
    If both A and B are NULL then stop and return.
    If either of them is NULL, then traverse the non null head till it becomes NULL.
    

    Code:

    public Node mergeLists(Node headA, Node headB) {
        Node merge = null;
        // If we have reached the end, then stop.
        while (headA != null || headB != null) {
            // if B is null then keep appending A, else check if value of A is lesser or equal than B
            if (headB == null || (headA != null && headA.data <= headB.data)) {
                // Add the new node, handle addition separately in a new method.
                merge = add(merge, headA.data);
                // Since A is <= B, Move head of A to next node
                headA = headA.next;
            // if A is null then keep appending B, else check if value of B is lesser than A
            } else if (headA == null || (headB != null && headB.data < headA.data)) {
                // Add the new node, handle addition separately in a new method.
                merge = add(merge, headB.data);
                // Since B is < A, Move head of B to next node
                headB = headB.next;
            }
        }
        return merge;
    }
    
    public Node add(Node head, int data) {
        Node end = new Node(data);
        if (head == null) {
            return end;
        }
    
        Node curr = head;
        while (curr.next != null) {
            curr = curr.next;
        }
    
        curr.next = end;
        return head;
    }
    

提交回复
热议问题