Tuesday, April 3, 2012

Program 3rd in C++

PROBLEM STATEMENT :


Implement a Queue data structure and provide enQ and deQ functionality where the only data structure you have to use is stack.


SOLUTION:


#include "iostream.h"
#include "cstdio"
#include "stack.h"
#include "cstdlib"
#include "string.h"
#include "unistd.h"


using namespace std;


stack enQ(stack st)
{


int num;


while(true)
{
cout<<"\n\nEnter Integer : ";
cin>>num;


if(cin.good())
{
st.push(num);
continue;
}
else
{
cin.clear();
cin.sync();
cin.ignore(numeric_limits <streamsize>::max(),'\n');
cout<<"\n\nEntered Invalid Input \n\n";
break;
}
}


return(st);


}


stack deQ(stack st)
{
while(!st.empty())
{
cout<<"\n\n Element
"<


st.pop();
}


return st;
}


int main()
{


stack frontst; //to enqueue elements
stack endst; //to dequeue elements
string choice;


while(true)
{
cout<<"\n\n Select Your Choice : ";
cout<<"\n\n 1. Enqueue ";
cout<<"\n\n 2. Dequeue ";
cout<<"\n\n 3. Exit ";
cout<<"\n\n Enter : ";
getline(cin,choice,'\n');


switch(choice[0])
{


case '1':


cout<<"\n\nEnter the elements to enqueue : ";
cout<<"\n(Press anyting other than integer to stop enqueuing)";
endst=enQ(endst);
break;


case '2':


if(frontst.empty() && !endst.empty())
{
while(!endst.empty())
{
frontst.push(endst.top());
endst.pop();
}
}
else
{
cout<<"\n\nThe queue is empty \n\n";
}
frontst=deQ(frontst);
break;


case '3':
exit(0);


default:
cout<<"\n\nEntered a wrong option \n\n";
}
}
}








No comments:

Post a Comment