Accessing the top of the stack
The top operation returns the value stored at the top of the stack. In the linked list implementation of a stack, the top item in the stack is the head of the linked list. The algorithm to get to the top of the stack is very simple. We have two cases to consider here.
1. Stack is empty
We can return -1 to indicate that there are no items in the stack. Ideally, we should be throwing an error, but for the sake of simplicity here, we return -1
Liking the course? Check our discounted plans to continue learning.