Open In App

Implement Stack using Array

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Stack is a linear data structurewhich 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:

  1. Initialize an array to represent the stack.
  2. Use the end of the array to represent the top of the stack.
  3. 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>usingnamespacestd;classStack{inttop,cap;int*a;public:Stack(intcap){this->cap=cap;top=-1;a=newint[cap];}~Stack(){delete[]a;}boolpush(intx){if(top>=cap-1){cout<<"Stack Overflow\n";returnfalse;}a[++top]=x;returntrue;}intpop(){if(top<0){cout<<"Stack Underflow\n";return0;}returna[top--];}intpeek(){if(top<0){cout<<"Stack is Empty\n";return0;}returna[top];}boolisEmpty(){returntop<0;}};intmain(){Stacks(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();}return0;}
C
// C program to create a stack with given capacity#include<stdio.h>#include<stdlib.h>structStack{inttop,cap;int*a;};structStack*createStack(intcap){structStack*stack=(structStack*)malloc(sizeof(structStack));stack->cap=cap;stack->top=-1;stack->a=(int*)malloc(cap*sizeof(int));returnstack;}voiddeleteStack(structStack*stack){free(stack->a);free(stack);}intisFull(structStack*stack){returnstack->top>=stack->cap-1;}intisEmpty(structStack*stack){returnstack->top<0;}intpush(structStack*stack,intx){if(isFull(stack)){printf("Stack Overflow\n");return0;}stack->a[++stack->top]=x;return1;}intpop(structStack*stack){if(isEmpty(stack)){printf("Stack Underflow\n");return0;}returnstack->a[stack->top--];}intpeek(structStack*stack){if(isEmpty(stack)){printf("Stack is Empty\n");return0;}returnstack->a[stack->top];}intmain(){structStack*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);return0;}
Java
// Java program to create a stack with given capacityclassStack{inttop,cap;int[]a;publicStack(intcap){this.cap=cap;top=-1;a=newint[cap];}publicbooleanpush(intx){if(top>=cap-1){System.out.println("Stack Overflow");returnfalse;}a[++top]=x;returntrue;}publicintpop(){if(top<0){System.out.println("Stack Underflow");return0;}returna[top--];}publicintpeek(){if(top<0){System.out.println("Stack is Empty");return0;}returna[top];}publicbooleanisEmpty(){returntop<0;}}publicclassMain{publicstaticvoidmain(String[]args){Stacks=newStack(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 capacityclassStack:def__init__(self,cap):self.cap=capself.top=-1self.a=[0]*capdefpush(self,x):ifself.top>=self.cap-1:print("Stack Overflow")returnFalseself.top+=1self.a[self.top]=xreturnTruedefpop(self):ifself.top<0:print("Stack Underflow")return0popped=self.a[self.top]self.top-=1returnpoppeddefpeek(self):ifself.top<0:print("Stack is Empty")return0returnself.a[self.top]defis_empty(self):returnself.top<0s=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=" ")whilenots.is_empty():print(s.peek(),end=" ")s.pop()
C#
// Create a stack with given capacityusingSystem;classStack{privateinttop,cap;privateint[]a;publicStack(intcap){this.cap=cap;top=-1;a=newint[cap];}publicboolPush(intx){if(top>=cap-1){Console.WriteLine("Stack Overflow");returnfalse;}a[++top]=x;returntrue;}publicintPop(){if(top<0){Console.WriteLine("Stack Underflow");return0;}returna[top--];}publicintPeek(){if(top<0){Console.WriteLine("Stack is Empty");return0;}returna[top];}publicboolIsEmpty(){returntop<0;}}classProgram{staticvoidMain(){Stacks=newStack(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 capacityclassStack{constructor(cap){this.cap=cap;this.top=-1;this.a=newArray(cap);}push(x){if(this.top>=this.cap-1){console.log("Stack Overflow");returnfalse;}this.a[++this.top]=x;returntrue;}pop(){if(this.top<0){console.log("Stack Underflow");return0;}returnthis.a[this.top--];}peek(){if(this.top<0){console.log("Stack is Empty");return0;}returnthis.a[this.top];}isEmpty(){returnthis.top<0;}}lets=newStack(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();}

Output
30 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>usingnamespacestd;intmain(){vector<int>s;// Push elementss.push_back(10);s.push_back(20);s.push_back(30);// Pop and print the top elementcout<<s.back()<<" popped from stack\n";s.pop_back();// Peek at the top elementcout<<"Top element is: "<<s.back()<<endl;// Print all elements in the stackcout<<"Elements present in stack: ";while(!s.empty()){cout<<s.back()<<" ";s.pop_back();}return0;}
Java
importjava.util.ArrayList;publicclassMain{publicstaticvoidmain(String[]args){ArrayList<Integer>s=newArrayList<>();// Push elementss.add(10);s.add(20);s.add(30);// Pop and print the top elementSystem.out.println(s.get(s.size()-1)+" popped from stack");s.remove(s.size()-1);// Peek at the top elementSystem.out.println("Top element is: "+s.get(s.size()-1));// Print all elements in the stackSystem.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 elementss.append(10)s.append(20)s.append(30)# Pop and print the top elementprint(f'{s[-1]} popped from stack')s.pop()# Peek at the top elementprint(f'Top element is: {s[-1]}')# Print all elements in the stackprint('Elements present in stack: ',end='')whiles:print(s.pop(),end=' ')
C#
usingSystem;usingSystem.Collections.Generic;classGfG{staticvoidMain(){Stack<int>s=newStack<int>();// Push elementss.Push(10);s.Push(20);s.Push(30);// Pop and print the top elementConsole.WriteLine(s.Peek()+" popped from stack");s.Pop();// Peek at the top elementConsole.WriteLine("Top element is: "+s.Peek());// Print all elements in the stackConsole.WriteLine("Elements present in stack: ");while(s.Count>0){Console.Write(s.Pop()+" ");}}}
JavaScript
// Using an array to simulate stack behaviorlets=[];// Push elementss.push(10);s.push(20);s.push(30);// Pop and print the top elementconsole.log(s[s.length-1]+" popped from stack");s.pop();// Peek at the top elementconsole.log("Top element is: "+s[s.length-1]);// Print all elements in the stackconsole.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.

Next Article
Practice Tags :

Similar Reads

close