A stack is a 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. A stack can be implemented with an array or a linked list. This post is to implement a stack using an array.

implement a stack using an array

you are here

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

Table of Content


Implement a stack using an array method – Push

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

Java

Javascript

Python

Doodle

stack array


Implement a stack using an array method – 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 the index of the top, then decrease the top by 1. Please note the element is still in the array until you replace it with another element or remove the array from the memory.

Java

Javascript

Python


Implement a stack using an array method – Peek

Peek is to return the value of the element at the 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 the stack starting from the 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.