A stack is Last-In-First-Out (LIFO) data structure in which only the top element can be accessed. The data is added by push and removed by pop on top. The operation of push, pop and peek all have O(1) complexity. Stack can be implemented with array, linked list. In this post, stack is implemented in array. Please check out linked list implementation if you are interested.

Table of Content


Push

To push an element in stack is to add element at the next available spot in array. First we need to define an array. In Java, if you use array (not ArrayList), you have to specify the maxSize of the array. If the array reaches the maxSize, we cannot add more element. The variable top is the index of the last element added.

Java

Javascript

Python

Doodle

stack array


Pop

To pop an element is to remove the last element in the array. First we check whether the stack is empty. If it is empty, the method should return. In Java array implementation, we return the element at index of top, then decrease top by 1. Please note the element is still in array until you replace with other element or remove array from the memory.

Java

Javascript

Python


Peek

Peek is to return the value of element at top position. The same as pop, we should check whether the stack is empty. If it is not empty, return the value.

Java

Javascript

Python


Print

Print is to print all elements in stack starting from top. A for loop is used to iterate through the array from last to first.

Java

Javascript

Python

Download Java, JavaScript and Python code
Stack (part 2) – linked list implementation
Stack animated visual
Data structures and Java collections