Assume that I have a singly linked list with sentinel. To remove the last element in O(1) time, I need to maintain handle to last 2 elements. But maintaining handle to last two elements complicates the add operation.
Is there a way to remove the last element of a singly linked list with sentinel in O(1) without maintaining handle to last 2 elements? I would much appreciate any sample code in java.
Thanks.
With a singly linked list implemented in the normal way will be an
O(N)operation.Retaining a handle on the last element isn’t that complicated, and singly-linked list implementations often do it so that you can add at the end in
O(1). However, maintaining the link to the last element in the face of anO(1)“remove last” operation is not possible.Think about it. Suppose I have somewhere to keep pointers to the last and 2nd to last nodes. When I remove the last node, I need to:
nextpointer in the 2nd to last node to be null,lastpointer to point to the 2nd to last node.secondToLastpointer to point to the node before it.But how do I do the last step without traversing the list from the start … which is an
O(N)operation?Now I suppose you could code your linked list so that removing the last element is
O(1)the first time you do it, andO(N)on subsequent times … until you add a new element at the end. But unless you’ve got an unusual use-case, this “optimization” won’t be worth it.You are probably better off using
java.util.LinkedListwhich uses a doubly-linked list, and has aremoveLast()method that isO(1).`