Stack (Data Structure) in C++



 #include<iostream>

using namespace std;


//STACK CLASS

class Stack

{

int top;

static const int SIZE= 5;

public:

int arr[SIZE];

Stack()

{

top=-1;

}

//PUSH

void push(int d)

{

if(top >= SIZE-1)

cout<<"Stack is full\n";

else{

arr[++top]=d;

}

}

//POP

int pop()

{

if(top<0)

{

cout<<"Stack is empty\n";

return 0;

}

else

return arr[top--];

}

//IS EMPTY?

bool isEmpty()

{

return top<0;

}

//IS FULL?

bool isFull()

{

return top>=SIZE-1;

}

//DISPLAY

void display(){

for(int i=0;i<=SIZE-1;i++){

cout<<arr[i]<<"\t";

}

}

//REVERSE PRINT

void reversePrint(){

if(top==-1 || top>SIZE-1)

cout<<"Operation cannot be performed."<<endl;

while(top>=0){

cout<<arr[top]<<"\t";

top--;

}

}

};


//MAIN

int main(){

Stack s; //An object "s" of class "Stack" is created

s.push(25);

s.push(10);

s.push(17);

s.push(19);

s.push(20);

s.push(50);

s.display();

cout<<endl;

s.reversePrint();

// cout<<s.pop();

// cout<<"\nlist is empty: "<<s.isEmpty();

return 0;

}

Comments