Featured Post

Trie implementation in C

Simple Stack using Arrays

A Simple stack using arrays.

#include <iostream>
#include <stdlib.h>
using namespace std;

class Base{
  
  public:
  virtual void push(int) = 0;
  virtual int pop() = 0;
};

class Stack : public Base{
 
  int *arr;
  int stack_len; 
  public:
    
   int top;
   Stack(int size);
  ~Stack();

 void push(int);
 int pop();
 void print_stack();
};

Stack::Stack(int size)
{
   arr = new int[size];
   top = -1;
   stack_len = size;
}

Stack::~Stack()
{
  delete[] arr;
}

void Stack::push(int item)
{
  if((top + 1) < stack_len)
  { 
    cout<<"Pushed "<<item<<endl;
    arr[++top] = item;
    print_stack();
  }
  else
    {
   cout<<"Stack Full!!!";
   exit(0);
 }
}

int Stack::pop()
{
  if(top!= -1)
  {
    cout<<"Popped "<<arr[top]<<endl;
    --top;
    print_stack();
  }
  else
    {
   cout<<"Stack Empty!!!";
   exit(0);
 }
}

void Stack::print_stack()
{
  int i;
  for(i = top ; i > -1 ; i--)
  {
    cout<<" "<<arr[i];
  }
  cout<<endl;
}

int main()
{
  Stack s1(5);

  s1.push(1);
  s1.push(2);
  s1.push(3);
  s1.push(4);
  
  s1.pop();
  s1.pop();

}

Comments