C++ Program to implement Dual Stack in a Single Structure or C++ Program to Implement Double Stack in a Single Array Structure

 //Program to implement Dual Stack in a Single Structure//

#include<iostream>

#define size 10

using namespace std;

struct dual

{

int topA,topB;

int stk[size];

}s;

class stack

{

public:

stack();

bool isemptyA();

bool isfullA();

void pushA(int);

int popA();

void displayA();

bool isemptyB();

bool isfullB();

void pushB(int);

int popB();

void displayB();

};

stack::stack()

{

s.topA=-1;

s.topB=size;

}

bool stack::isemptyA()

{

if(s.topA==-1 || s.topB==0)

return true;

else

return false;

}

bool stack::isfullA()

{

if(s.topA==size || s.topA+1==s.topB || s.topB==0)

return true;

else

return false;

}

bool stack::isemptyB()

{

if(s.topB==size || s.topA==size-1)

return true;

else

return false;

}

bool stack::isfullB()

{

if(s.topB==0 || s.topB-1==s.topA ||s.topA==size-1)

return true;

else

return false;

}

void stack::pushA(int m)

{

bool k=isfullA();

if(k==true)

{

cout<<"Stack A is Overflow"<<endl;

}

else

{

++s.topA;

s.stk[s.topA]=m;

}

}

void stack::pushB(int m)

{

bool k=isfullB();

if(k==true)

{

cout<<"Stack B is Overflow"<<endl;

}

else

{

--s.topB;

s.stk[s.topB]=m;

}

}

int stack::popA()

{

bool l=isemptyA();

if(l==true)

{

return 0;

}

else

{

int n=s.stk[s.topA];

s.topA--;

return n;

}

}

int stack::popB()

{

bool l=isemptyB();

if(l==true)

{

return 0;

}

else

{

int n=s.stk[s.topB];

s.topB++;

return n;

}

}

void stack::displayA()

{

bool p=isemptyA();

if(p==true)

cout<<"The Stack A is Underflow"<<endl;

else

{

cout<<"The Stack A is"<<endl;

for(int i=s.topA;i>=0;i--)

{

cout<<s.stk[i]<<endl;

}

}

}

void stack::displayB()

{

bool p=isemptyB();

if(p==true)

cout<<"The Stack B is Underflow"<<endl;

else

{

cout<<"The Stack B is"<<endl;

for(int i=s.topB;i<=size-1;i++)

{

cout<<s.stk[i]<<endl;

}

}

}

int main()

{

stack obj;

int ch,p,o;

do

{

cout<<"Choose your option"<<endl;

cout<<"1.Push an element to Stack A"<<endl;

cout<<"2.Pop an element from Stack A"<<endl;

cout<<"3.Display the Stack A"<<endl;

cout<<"4.Push an element to Stack B"<<endl;

cout<<"5.Pop an element from Stack B"<<endl;

cout<<"6.Display the Stack B"<<endl;

cout<<"7.Exit"<<endl;

cin>>ch;

switch(ch)

{

case 1:

cout<<"Enter the element to Push to Stack A"<<endl;

cin>>o;

obj.pushA(o);

break;

case 2:

p=obj.popA();

if(p==0)

cout<<"Stack A is Underflow"<<endl;

else

cout<<"The popped element from Stack A is "<<p<<endl;

break;

case 3:

obj.displayA();

break;

case 4:

cout<<"Enter the element to Push to Stack B"<<endl;

cin>>o;

obj.pushB(o);

break;

case 5:

p=obj.popB();

if(p==0)

cout<<"Stack B is Underflow"<<endl;

else

cout<<"The popped element from Stack B is "<<p<<endl;

break;

case 6:

obj.displayB();

break;

case 7:

exit(0);

break;

default:

cout<<"Invalid Input"<<endl;

break;

}

}

while(ch!=7);

return 0;

}



Comments