#include using namespace std;
class stack { public: stack(); ~stack(); void Push(int inData); int Pop(); void display(); bool IsEmpty(); protected: typedef struct nodeT { int data; struct nodeT *next; }node; node *firstElement; };
//Class method implementation now stack::stack() { firstElement = NULL; return; }
stack::~stack() { node *next; while(firstElement) { next=firstElement->next; delete firstElement; firstElement=firstElement->next; } return; }
void stack::Push(int inData) { node *newNode = new node; newNode->data=inData; newNode->next=firstElement; firstElement = newNode; return; }
//Note that the Pop operation is intended to return the data stored in the top most node and free
//that space in the stack int stack::Pop() { node *nodeToPop; int data; nodeToPop=firstElement; firstElement=firstElement->next; data=nodeToPop->data; delete nodeToPop; return data; }
bool stack::IsEmpty() { if(!firstElement) return 1; else return 0; }
void stack::display() { node *ptr; ptr=firstElement; if(ptr) { cout<<"The stack elements are: "<<endl; while(ptr) { cout<data<<endl; ptr=ptr->next; } } else { cout<<"There are no elements in the stack!!!!"<<endl; } }
void main() { stack objStack; int indata=0, choice=1; while(choice!=0) { cout<<"Stack Operations Main Menu: 1.Push 2.Pop 3.IsEmpty 4.IsFull 0.Exit"
<<endl; cin>>choice; switch(choice) { case 0: exit(1); //Normal program Termination case 1: cout<<"Enter the number to Push: "; cin>>indata; objStack.Push(indata); break; case 2: if(!objStack.IsEmpty()) { cout<<"The number popped from the stack is: "<<objStack.Pop()
<<endl; } else {cout<<"Cannot pop from an empty stack!!!"<<endl;} break; case 3: cout<<"Checking if the stack is empty…"; if(objStack.IsEmpty()) { cout<<"The stack is empty."<<endl; } else { cout<<"The stack is not empty"<<endl;; } break; case 4: //TO Do default: cout<<"Illegal Action. Please try again!!!"<<endl; } objStack.display(); cin.get(); } }
|