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

后端 未结 26 3032
有刺的猬
有刺的猬 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:13

    This could be done without creating the extra node, with just an another Node reference passing to the parameters (Node temp).

    private static Node mergeTwoLists(Node nodeList1, Node nodeList2, Node temp) {
        if(nodeList1 == null) return nodeList2;
        if(nodeList2 == null) return nodeList1;
    
        if(nodeList1.data <= nodeList2.data){
            temp = nodeList1;
            temp.next = mergeTwoLists(nodeList1.next, nodeList2, temp);
        }
        else{
            temp = nodeList2;
            temp.next = mergeTwoLists(nodeList1, nodeList2.next, temp);
        }
        return temp;
    }
    

提交回复
热议问题