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

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

    void printLL(){
        NodeLL cur = head;
        if(cur.getNext() == null){
            System.out.println("LL is emplty");
        }else{
            //System.out.println("printing Node");
            while(cur.getNext() != null){
                cur = cur.getNext();
                System.out.print(cur.getData()+ " ");
    
            }
        }
        System.out.println();
    }
    
    void mergeSortedList(NodeLL node1, NodeLL node2){
        NodeLL cur1 = node1.getNext();
        NodeLL cur2 = node2.getNext();
    
        NodeLL cur = head;
        if(cur1 == null){
            cur = node2;
        }
    
        if(cur2 == null){
            cur = node1;
        }       
        while(cur1 != null && cur2 != null){
    
            if(cur1.getData() <= cur2.getData()){
                cur.setNext(cur1);
                cur1 = cur1.getNext();
            }
            else{
                cur.setNext(cur2);
                cur2 = cur2.getNext();
            }
            cur = cur.getNext();
        }       
        while(cur1 != null){
            cur.setNext(cur1);
            cur1 = cur1.getNext();
            cur = cur.getNext();
        }       
        while(cur2 != null){
            cur.setNext(cur2);
            cur2 = cur2.getNext();
            cur = cur.getNext();
        }       
        printLL();      
    }
    

提交回复
热议问题