Stack implementation using array in C++

In this tutorial, we will learn how to implement a stack using an array in cpp. A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. This means the last element inserted is the first one to be removed. 

Operations :

  1. PUSH:- This operation is related to inserting an element onto the top of the stack.
  2. POP:- This operation is related to the deletion of an element from the top of the stack.
  3. TOP:- This operation is used to display the element at the top of the stack.
  4. EMPTY:- This operation is used to check whether the stack is empty or not

Code :

#include <iostream>
using namespace std;
#define n 100
class stack {

  int* arr;
  int top;
  public:

    stack() {
    arr = new int[n];
      top = -1;
  }

  void push (int x)
  {
    if (top == n - 1)
      {
        cout << "stack overflow" << endl;
        return;
      }
    top++;
    arr[top] = x;
    cout <<"Element pushed to stack : "<< x <<endl;
  }

  int pop ()
  {
    if (top == -1)
      {
        cout << "no elements to pop" << endl;
      }
    int x = arr[top];
        top--;
        cout<<"Element popped from stack : "<< x <<endl;
        return x;
  }

  int Top ()
  {
    if (top == -1)
      {
        cout << "stack is empty" << endl;
        return -1;
      }
    cout<<"Element at the top of stack : "<< arr[top] <<endl;
     return arr[top];
  }

  bool empty ()
  {
    return top == -1;
  }
  
};

int
main ()
{
  stack st;
  st.push (2);
  st.push (6);
  st.pop();
  st.push (9);
  st.Top();
  cout<<st.empty()<<endl;
  return 0;
}

 

Explanation:

  1. The Stack class has two member variables: toparr.
    • top: Index of the top element.
    • arr: Array to store elements.
  2. The push() function adds an element to the top of the stack. It increments the top before adding the element.
  3. The pop() function removes and returns the top element of the stack. It decrements top after removing the element.
  4. The peek() function returns the top element without removing it.
  5. The empty() function checks whether the stack is empty or not.

Output:

Element pushed to stack : 2
Element pushed to stack : 6
Element popped from stack : 6
Element pushed to stack : 9
Element at the top of the stack : 9
0

Summary:

This implementation provides a basic understanding of stack operations using an array.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top