Implement a Queue using Stack
#include<iostream>
#include<vector>
using namespace std;
class Stack
{
private:
vector<int> theArray;
int topElement;
public:
Stack()
{
topElement = -1;
}
bool push(int number)
{
theArray.push_back(number);
topElement = theArray.back();
return true;
}
int pop()
{
if(isEmpty())
return -1000;
else
{
int a = theArray.back();
theArray.pop_back();
topElement = theArray.back();
return a;
}
}
bool isEmpty()
{
if(theArray.empty())
return true;
else
return false;
}
int top()
{
return topElement;
}
void displayStack()
{
for(int i=0; i<thearray.size(); i++)
{
cout<<" "<<thearray[i];
}
}
};
Stack s1,s2;
void enQueue(int number)
{
s1.push(number);
}
int deQueue()
{
if(s2.isEmpty())
{
while(!s1.isEmpty())
{
s2.push(s1.pop());
}
}
return s2.pop();
}
void displayQueue()
{
while(!s2.isEmpty())
{
s1.push(s2.pop());
}
s1.displayStack();
}
int main()
{
enQueue(1);
enQueue(2);
cout << deQueue()<<endl;
cout << deQueue()<<endl;
cout << deQueue()<<endl;
displayQueue();
return 0;
}
#include<iostream>
#include<vector>
using namespace std;
class Stack
{
private:
vector<int> theArray;
int topElement;
public:
Stack()
{
topElement = -1;
}
bool push(int number)
{
theArray.push_back(number);
topElement = theArray.back();
return true;
}
int pop()
{
if(isEmpty())
return -1000;
else
{
int a = theArray.back();
theArray.pop_back();
topElement = theArray.back();
return a;
}
}
bool isEmpty()
{
if(theArray.empty())
return true;
else
return false;
}
int top()
{
return topElement;
}
void displayStack()
{
for(int i=0; i<thearray.size(); i++)
{
cout<<" "<<thearray[i];
}
}
};
Stack s1,s2;
void enQueue(int number)
{
s1.push(number);
}
int deQueue()
{
if(s2.isEmpty())
{
while(!s1.isEmpty())
{
s2.push(s1.pop());
}
}
return s2.pop();
}
void displayQueue()
{
while(!s2.isEmpty())
{
s1.push(s2.pop());
}
s1.displayStack();
}
int main()
{
enQueue(1);
enQueue(2);
cout << deQueue()<<endl;
cout << deQueue()<<endl;
cout << deQueue()<<endl;
displayQueue();
return 0;
}
No comments:
Post a Comment