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
C++ Program to Implement Stack using array
Stack is the fundamental data structure that can operates the under the Last In, First Out (LIFO) principle. This means that the last element added to the stack is the first one to be removed. Implementing the stack using the array is one of the most straightforward methods in the terms of the both
4 min read
Searching in Array
Searching is one of the most common operations performed in an array. Array searching can be defined as the operation of finding a particular element or a group of elements in the array. There are several searching algorithms. The most commonly used among them are: Linear Search Binary Search Ternar
4 min read
String Arrays in Java
A String Array in Java is an array that stores string values. The string is nothing but an object representing a sequence of char values. Strings are immutable in Java, this means their values cannot be modified once created.When we create an array of type String in Java, it is called a String Array
5 min read
What is Wiring in Arrays?
Prerequisite: Arrays Arrays are used to create lists of elements with the same data type and store them in adjacent regions of memory. Arrays are just the grouping of elements of the same data type. 1-Dimensional arrays, 2-Dimensional arrays, and 3-Dimensional arrays are just a few of the several ty
11 min read
Array Sorting - Practice Problems
Sorting an array means arranging the elements of the array in a certain order. Generally sorting in an array is done to arrange the elements in increasing or decreasing order. Problem statement: Given an array of integers arr, the task is to sort the array in ascending order and return it, without u
9 min read
Implement Arrays in different Programming Languages
Arrays are one of the basic data structures that should be learnt by every programmer. Arrays stores a collection of elements, each identified by an index or a key. They provide a way to organize and access a fixed-size sequential collection of elements of the same type. In this article, we will lea
5 min read
One Dimensional Arrays in C
In C, an array is a collection of elements of the same type stored in contiguous memory locations. This organization allows efficient access to elements using their index. Arrays can also be of different types depending upon the direction/dimension they can store the elements. It can be 1D, 2D, 3D,
5 min read
Arrays and Strings in C++
Arrays An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar types of elements as in the data type must be the same for all elements. They can be used to store the collection
5 min read
One Dimensional Arrays in C++
One-dimensional arrays are like a row of boxes where you can store things where each box can hold one item, such as a number or a word. For example, in an array of numbers, the first box might hold 5, the second 10, and so on. You can easily find or change what's in each box by referring to its posi
6 min read
Practice questions on Arrays
In this article, we will discuss some important concepts related to arrays and problems based on that. Before understanding this, you should have basic idea about Arrays.Type 1. Based on array declaration - These are few key points on array declaration: A single dimensional array can be declared as
6 min read