Deleting any node from a single linked list when only pointer to that node is given

前端 未结 6 1049
天涯浪人
天涯浪人 2020-12-08 05:44

This is a question posed to me in an interview.

\"A single linked list is there in the memory. You have to delete a node. You need to write a function to delete that

6条回答
  •  一向
    一向 (楼主)
    2020-12-08 06:11

     public void removeNode(Node node){
    
            /* if no node return null */
            if(node==null) return;
    
            /* if only 1 node then delete node */
            if(node.getNext()==null) {
                node = null;
                return ;
            }
    
            /* copy next node data to this node */
            node.data = node.getNext().data();
    
            /* store the next next node */
            Node second = node.getNext().getNext();
    
            /* remove next node */
            removeNode(node.getNext());
    
            /* set the copied node as next */
            node.setNext(second);
         }
    

提交回复
热议问题