#include<iostream>
#include<stack>
using namespace std;
#define NUM 5
//仅用栈实现一个队列结构
class MyQueue
{
private:
stack<int> *stackk,*help;
public:
MyQueue();
~MyQueue();
void push(int element);
int peek();
int pop();
void rotation();
};
MyQueue::MyQueue()
{
stackk = new stack<int>;
help = new stack<int>;
}
MyQueue::~MyQueue()
{
delete stackk;
delete help;
}
void MyQueue::push(int element)
{
stackk->push(element);
//rotation();
}
int MyQueue::peek()
{
if(help->empty())
{
cout<<"队列中没有元素"<<endl;
return -1;
}
rotation();
int ret = help->top();
return ret;
}
int MyQueue::pop()
{
if(help->empty() && stackk->empty())
{
cout<<"队列中没有元素"<<endl;
return -1;
}
rotation();
int ret = help->top();
help->pop();
return ret;
}
void MyQueue::rotation()
{
while(stackk->empty() == false && help->empty())
{
help->push(stackk->top());
stackk->pop();
}
}
int main()
{
MyQueue m1;
m1.push(1);
m1.push(2);
m1.push(3);
m1.push(4);
m1.push(5);
for(int i=0;i<5;i++)
cout<<m1.pop()<<endl;
return 0;
}
C++只用队列实现栈
最新推荐文章于 2024-08-07 17:27:28 发布