The other choice is have the top element be at position n − 1 when there are n elements in the stack. In other words, as elements are pushed onto the stack, they are appended to the tail of the list. Method pop removes the tail element. In this case, the cost for each push or pop operation is only Θ(1). For the implementation of Figure 4.18, top is defined to be the array index of the first free position in the stack. Thus, an empty stack has top set to 0, the first available free position in the array
Methods push and pop simply place an element into, or remove an element from, the array position indicated by top. Because top is assumed to be at the first free position, push first inserts its value into the top position and then increments top, while pop first decrements top and then removes the top element.