Implement Stack using Array
Last Updated :
21 Mar, 2025
Stack is a linear data structure which follows LIFO principle. To implement a stack using an array, initialize an array and treat its end as the stack’s top. Implement push (add to end), pop (remove from end), and peek (check end) operations, handling cases for an empty or full stack.
Step-by-step approach:
- Initialize an array to represent the stack.
- Use the end of the array to represent the top of the stack.
- Implement push (add to end), pop (remove from the end), and peek (check end) operations, ensuring to handle empty and full stack conditions.
Here are the following operations of implement stack using array:
Push Operation in Stack:
Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition.
- Before pushing the element to the stack, we check if the stack is full .
- If the stack is full (top == capacity-1) , then Stack Overflows and we cannot insert the element to the stack.
- Otherwise, we increment the value of top by 1 (top = top + 1) and the new value is inserted at top position .
- The elements can be pushed into the stack till we reach the capacity of the stack.
Pop Operation in Stack:
Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
- Before popping the element from the stack, we check if the stack is empty .
- If the stack is empty (top == -1), then Stack Underflows and we cannot remove any element from the stack.
- Otherwise, we store the value at top, decrement the value of top by 1 (top = top – 1) and return the stored top value.
Top or Peek Operation in Stack:
Returns the top element of the stack.
- Before returning the top element from the stack, we check if the stack is empty.
- If the stack is empty (top == -1), we simply print “Stack is empty”.
- Otherwise, we return the element stored at index = top .
isEmpty Operation in Stack:
Returns true if the stack is empty, else false.=
- Check for the value of top in stack.
- If (top == -1) , then the stack is empty so return true .
- Otherwise, the stack is not empty so return false .
isFull Operation in Stack :
Returns true if the stack is full, else false.
- Check for the value of top in stack.
- If (top == capacity-1), then the stack is full so return true .
- Otherwise, the stack is not full so return false.
Implementation using Fixed Sized Array
In this implementation, we use a fixed sized array. We take capacity as argument when we create a stack. We create an array with size equal to given capacity. If number of elements go beyond capacity, we throw an overflow error.
C++
// C++ program to create a stack with
// given capacity
#include <bits/stdc++.h>
using namespace std;
class Stack {
int top, cap;
int *a;
public:
Stack(int cap) {
this->cap = cap;
top = -1;
a = new int[cap];
}
~Stack() {
delete[] a;
}
bool push(int x) {
if (top >= cap - 1) {
cout << "Stack Overflow\n";
return false;
}
a[++top] = x;
return true;
}
int pop() {
if (top < 0) {
cout << "Stack Underflow\n";
return 0;
}
return a[top--];
}
int peek() {
if (top < 0) {
cout << "Stack is Empty\n";
return 0;
}
return a[top];
}
bool isEmpty() {
return top < 0;
}
};
int main() {
Stack s(5);
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " popped from stack\n";
cout << "Top element is: " << s.peek() << endl;
cout << "Elements present in stack: ";
while (!s.isEmpty()) {
cout << s.peek() << " ";
s.pop();
}
return 0;
}
C
// C program to create a stack with given capacity
#include <stdio.h>
#include <stdlib.h>
struct Stack {
int top, cap;
int *a;
};
struct Stack* createStack(int cap) {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->cap = cap;
stack->top = -1;
stack->a = (int*)malloc(cap * sizeof(int));
return stack;
}
void deleteStack(struct Stack* stack) {
free(stack->a);
free(stack);
}
int isFull(struct Stack* stack) {
return stack->top >= stack->cap - 1;
}
int isEmpty(struct Stack* stack) {
return stack->top < 0;
}
int push(struct Stack* stack, int x) {
if (isFull(stack)) {
printf("Stack Overflow\n");
return 0;
}
stack->a[++stack->top] = x;
return 1;
}
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
return 0;
}
return stack->a[stack->top--];
}
int peek(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is Empty\n");
return 0;
}
return stack->a[stack->top];
}
int main() {
struct Stack* s = createStack(5);
push(s, 10);
push(s, 20);
push(s, 30);
printf("%d popped from stack\n", pop(s));
printf("Top element is: %d\n", peek(s));
printf("Elements present in stack: ");
while (!isEmpty(s)) {
printf("%d ", peek(s));
pop(s);
}
deleteStack(s);
return 0;
}
Java
// Java program to create a stack with given capacity
class Stack {
int top, cap;
int[] a;
public Stack(int cap) {
this.cap = cap;
top = -1;
a = new int[cap];
}
public boolean push(int x) {
if (top >= cap - 1) {
System.out.println("Stack Overflow");
return false;
}
a[++top] = x;
return true;
}
public int pop() {
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
return a[top--];
}
public int peek() {
if (top < 0) {
System.out.println("Stack is Empty");
return 0;
}
return a[top];
}
public boolean isEmpty() {
return top < 0;
}
}
public class Main {
public static void main(String[] args) {
Stack s = new Stack(5);
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " popped from stack");
System.out.println("Top element is: " + s.peek());
System.out.print("Elements present in stack: ");
while (!s.isEmpty()) {
System.out.print(s.peek() + " ");
s.pop();
}
}
}
Python
# Create a stack with given capacity
class Stack:
def __init__(self, cap):
self.cap = cap
self.top = -1
self.a = [0] * cap
def push(self, x):
if self.top >= self.cap - 1:
print("Stack Overflow")
return False
self.top += 1
self.a[self.top] = x
return True
def pop(self):
if self.top < 0:
print("Stack Underflow")
return 0
popped = self.a[self.top]
self.top -= 1
return popped
def peek(self):
if self.top < 0:
print("Stack is Empty")
return 0
return self.a[self.top]
def is_empty(self):
return self.top < 0
s = Stack(5)
s.push(10)
s.push(20)
s.push(30)
print(s.pop(), "popped from stack")
print("Top element is:", s.peek())
print("Elements present in stack:", end=" ")
while not s.is_empty():
print(s.peek(), end=" ")
s.pop()
C#
// Create a stack with given capacity
using System;
class Stack {
private int top, cap;
private int[] a;
public Stack(int cap) {
this.cap = cap;
top = -1;
a = new int[cap];
}
public bool Push(int x) {
if (top >= cap - 1) {
Console.WriteLine("Stack Overflow");
return false;
}
a[++top] = x;
return true;
}
public int Pop() {
if (top < 0) {
Console.WriteLine("Stack Underflow");
return 0;
}
return a[top--];
}
public int Peek() {
if (top < 0) {
Console.WriteLine("Stack is Empty");
return 0;
}
return a[top];
}
public bool IsEmpty() {
return top < 0;
}
}
class Program {
static void Main() {
Stack s = new Stack(5);
s.Push(10);
s.Push(20);
s.Push(30);
Console.WriteLine(s.Pop() + " popped from stack");
Console.WriteLine("Top element is: " + s.Peek());
Console.Write("Elements present in stack: ");
while (!s.IsEmpty()) {
Console.Write(s.Peek() + " ");
s.Pop();
}
}
}
JavaScript
// Create a stack with given capacity
class Stack {
constructor(cap) {
this.cap = cap;
this.top = -1;
this.a = new Array(cap);
}
push(x) {
if (this.top >= this.cap - 1) {
console.log("Stack Overflow");
return false;
}
this.a[++this.top] = x;
return true;
}
pop() {
if (this.top < 0) {
console.log("Stack Underflow");
return 0;
}
return this.a[this.top--];
}
peek() {
if (this.top < 0) {
console.log("Stack is Empty");
return 0;
}
return this.a[this.top];
}
isEmpty() {
return this.top < 0;
}
}
let s = new Stack(5);
s.push(10);
s.push(20);
s.push(30);
console.log(s.pop() + " popped from stack");
console.log("Top element is:", s.peek());
console.log("Elements present in stack:");
while (!s.isEmpty()) {
console.log(s.peek() + " ");
s.pop();
}
Output30 popped from stack
Top element is: 20
Elements present in stack: 20 10
Implementation using Dynamic Sized Array
In this implementation, we use a dynamic sized array like vector in C++, ArrayList in Java, List in Python and Array in JavaScript. This is a simpler implementation but less efficient compared to the previous one if we know capacity in advance.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> s;
// Push elements
s.push_back(10);
s.push_back(20);
s.push_back(30);
// Pop and print the top element
cout << s.back() << " popped from stack\n";
s.pop_back();
// Peek at the top element
cout << "Top element is: " << s.back() << endl;
// Print all elements in the stack
cout << "Elements present in stack: ";
while (!s.empty()) {
cout << s.back() << " ";
s.pop_back();
}
return 0;
}
Java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> s = new ArrayList<>();
// Push elements
s.add(10);
s.add(20);
s.add(30);
// Pop and print the top element
System.out.println(s.get(s.size() - 1) + " popped from stack");
s.remove(s.size() - 1);
// Peek at the top element
System.out.println("Top element is: " + s.get(s.size() - 1));
// Print all elements in the stack
System.out.print("Elements present in stack: ");
while (!s.isEmpty()) {
System.out.print(s.get(s.size() - 1) + " ");
s.remove(s.size() - 1);
}
}
}
Python
s = []
# Push elements
s.append(10)
s.append(20)
s.append(30)
# Pop and print the top element
print(f'{s[-1]} popped from stack')
s.pop()
# Peek at the top element
print(f'Top element is: {s[-1]}')
# Print all elements in the stack
print('Elements present in stack: ', end='')
while s:
print(s.pop(), end=' ')
C#
using System;
using System.Collections.Generic;
class GfG {
static void Main() {
Stack<int> s = new Stack<int>();
// Push elements
s.Push(10);
s.Push(20);
s.Push(30);
// Pop and print the top element
Console.WriteLine(s.Peek() + " popped from stack");
s.Pop();
// Peek at the top element
Console.WriteLine("Top element is: " + s.Peek());
// Print all elements in the stack
Console.WriteLine("Elements present in stack: ");
while (s.Count > 0) {
Console.Write(s.Pop() + " ");
}
}
}
JavaScript
// Using an array to simulate stack behavior
let s = [];
// Push elements
s.push(10);
s.push(20);
s.push(30);
// Pop and print the top element
console.log(s[s.length - 1] + " popped from stack");
s.pop();
// Peek at the top element
console.log("Top element is: " + s[s.length - 1]);
// Print all elements in the stack
console.log("Elements present in stack: ");
while (s.length > 0) {
console.log(s[s.length - 1] + " ");
s.pop();
}
Comparison of the two Implementations
- The first implementation should be preferred if we know capacity or have a close upper bound on number of elements.
- The second one is simple and has amortized (average over n operations) time complexities as O(1) for push and pop. However it can have a particular push and pop very costly.
Complexity Analysis:
- Time Complexity:
push
: O(1)pop
: O(1)peek
: O(1)is_empty
: O(1)- is_full: O(1)
- Auxiliary Space: O(n), where n is the number of items in the stack.
Advantages of Array Implementation:
- Easy to implement.
- Memory is saved as pointers are not involved.
Disadvantages of Array Implementation:
- It is not dynamic i.e., it doesn’t grow and shrink depending on needs at runtime. [But in case of dynamic sized arrays like vector in C++, list in Python, ArrayList in Java, stacks can grow and shrink with array implementation as well]. But with dynamic sized arrays, we get amortized time complexity as O(1), not the worst case. If we use linked list, we get worst case time complexities as O(1).
- The total size of the stack must be defined beforehand.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read