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. This is stack implemented using array.

stack as array

you are here

Part 1 – Stack implementation using array
Part 2 – Stack implementation using linked list

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
Data structures and Java collections

What is the difference between a stack and a call stack?

A stack is a Last-In-First-Out data structure. The last item added to a stack will be the first one to be removed.
A call stack is a stack data structure used by computer programs to keep track of the sequence of function calls.