codeintuition-logo

Accessing the top of the stack


The top operation is one of the most widely used stack operations. It just returns the value stored at the topIndex of the stack. We always store the index of the top item of the stack in the array implementation, and for this operation, we need to return that index's value to the user. 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.