Implement Stack using Array (original) (raw)

Last Updated : 21 Mar, 2025

Try it on GfG Practice redirect icon

**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.

**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.

**Top or Peek Operation in Stack:

Returns the top element of the stack.

**isEmpty Operation in Stack:

Returns true if the stack is empty, else false.=

isFull **Operation in Stack :

Returns true if the stack is full, else 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(); }

`

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> using namespace std;

int main() { vector 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 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 s = new Stack();

    // 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

Complexity Analysis:

Advantages of Array Implementation:

Disadvantages of Array Implementation: