0
votes

We cannot easily delete the last node of a singly linked list. Even if we maintain a tail reference directly to the last node of the list, we must be able to access the node before the last node in order to remove the last node. But we cannot reach the node before the tail by following next links from the tail. The only way to access this node is to start from the head of the list and search all the way through the list. But such a sequence of link-hopping operations could take a long time.

2
I think you may be trying to answer someone else's question rather than create your own, but, if not, yes you are absolutely correct. It would be much less time consuming with a doubly linked list with a previous node pointer. - jjo
In singly linked list data structure, to delete any node in the list you have to start traversing the list from the head of the list and keep track of previous node of current node. - H.S.

2 Answers

0
votes

It will at least take O(n) time complexity to delete the last node in singly linked list.

But, this can be done in O(constant), by using a doubly linked list.

0
votes

Simply take a for loop that start from i=0 upto i<size where size is the number of nodes in that singly linked list. The condition next.getNext().getNext()==null in the code below checks whether the node after the next node has reference null for next node Reference that is tail Then it simply sets null in next node reference.

See the method below.

public void removeLast() {
        Node<E> next=head;
        for(int i=0; i<size; i++) {
            if(next.getNext().getNext()==null) {
                next.getNext().setNext(null);
                tail=next.getNext();
                size--;
            }
            next=next.getNext();
        }
    }

Note: getNext() returns reference of next node.

Since getNext() returns Node type reference so we can call next.getNext().getNext()

size keeps count of nodes create so far.