Stack & Queue Using Arrays in C++

Stack & Queue Using Arrays in C++ | Code & Explanation

📦 Stack and Queue Implementation Using Arrays in C++

Stack and Queue are fundamental data structures in programming. In this tutorial, we'll explore how to implement both using arrays in C++ along with example code, output, and explanation.

🔁 What is a Stack?

A Stack follows the LIFO (Last In, First Out) principle. The last element added is the first one to be removed. It supports:

  • push() – insert element
  • pop() – remove element
  • peek() – view the top element

📋 Stack Using Array – C++ Code


#include <iostream>
using namespace std;

#define SIZE 5

class Stack {
    int arr[SIZE];
    int top;
public:
    Stack() { top = -1; }

    void push(int x) {
        if (top == SIZE - 1)
            cout << "Stack Overflow\n";
        else
            arr[++top] = x;
    }

    void pop() {
        if (top == -1)
            cout << "Stack Underflow\n";
        else
            top--;
    }

    void display() {
        for (int i = top; i >= 0; i--)
            cout << arr[i] << " ";
        cout << endl;
    }
};

int main() {
    Stack s;
    s.push(10);
    s.push(20);
    s.push(30);
    s.display();
    s.pop();
    s.display();
    return 0;
}
    

📝 Stack Output

30 20 10
20 10

📚 What is a Queue?

A Queue uses the FIFO (First In, First Out) principle. The first element added is the first one removed. It supports:

  • enqueue() – add element at the rear
  • dequeue() – remove element from the front
  • display() – print all elements

📋 Queue Using Array – C++ Code


#include <iostream>
using namespace std;

#define SIZE 5

class Queue {
    int arr[SIZE];
    int front, rear;
public:
    Queue() {
        front = -1;
        rear = -1;
    }

    void enqueue(int x) {
        if (rear == SIZE - 1)
            cout << "Queue Overflow\n";
        else {
            if (front == -1) front = 0;
            arr[++rear] = x;
        }
    }

    void dequeue() {
        if (front == -1 || front > rear)
            cout << "Queue Underflow\n";
        else
            front++;
    }

    void display() {
        for (int i = front; i <= rear; i++)
            cout << arr[i] << " ";
        cout << endl;
    }
};

int main() {
    Queue q;
    q.enqueue(10);
    q.enqueue(20);
    q.enqueue(30);
    q.display();
    q.dequeue();
    q.display();
    return 0;
}
    

📝 Queue Output

10 20 30
20 30

💡 Final Thoughts

Using arrays for Stack and Queue is great for learning, though in real-world scenarios, dynamic structures (like vectors or linked lists) offer more flexibility. These implementations give a solid foundation for understanding how data structures manage memory and data flow.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences