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

两盒软妹~` 提交于 2021-01-29 17:47:06

问题


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}.


回答1:


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.



来源:https://stackoverflow.com/questions/58104138/delete-a-node-from-singly-linked-list-at-any-index-using-a-single-method-functio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!