简体   繁体   中英

Delete a node from Singly Linked list at any index using a single method/function in java

I want to create and delete a node from the singly linked list in java. The deleting method will take the index of node and delete that node.

The logic is working but it is not deleting the node at first index (0) how do i modify this code so that it can delete node at any position without using extra loops. I know that I am using starting index as 1 in code but I can not riddle this that if entered index is zero then how the program can delete the "previousNode" using the same loop. It will require another loop (based on this logic). Is there a way to remove this extra loop

public E deleteNode(int t) throws IndexOutOfBoundsException{
        if(size==0) 
            return null;

        if(t>=size) 
            throw new IndexOutOfBoundsException("Invalid Input");

        Node<E> previousNode=head;
        Node<E> currentNode=previousNode.getNext();
        int currentIndex=1;


        while(currentIndex<t){

            previousNode=previousNode.getNext();
            currentNode=previousNode.getNext();
            currentIndex++;
        }
        previousNode.setNext(currentNode.getNext());
        size--;
        return currentNode.getElement();
    }

If user enters the index 0, then the output of {1,2,3,4} should be {2,3,4} but I get {1,3,4}.

One option would be to handle it as a special case as it requires updating head .

if (t == 0) {
    head = head.getNext();
}
//rest of your code..
Node<E> previousNode=head;
//...

Or, you can do like

Node<E> previousNode = null;
Node<E> currentNode = head;
int currentIndex = 0;

while(currentIndex < t) {
    previousNode = currentNode;
    currentNode = currentNode.getNext();
    currentIndex++;
}
if (previousNode == null) { //removing first node
    head = head.getNext();
} else {
    previousNode.setNext(currentNode.getNext());
}
size--;
return currentNode.getElement();

But anyway you need to handle it as a special case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM