#include<iostream>
#include<queue>
using namespace std;
#define NUM 5
//仅用队列实现一个栈结构
class MyStack
{
private:
queue<int> *q1,*q2;
public:
MyStack();
~MyStack();
void rotation();
void swap();
void push(int);
int pop();
int peek();
};
MyStack::MyStack()
{
q1 = new queue<int>;
q2 = new queue<int>;
}
MyStack::~MyStack()
{
delete q1;
delete q2;
}
void MyStack::rotation()
{
while(q1->size() > 1)
{
int tmp = q1->front();
//cout<<tmp<<endl;
q1->pop();
q2->push(tmp);
}
}
void MyStack::swap()
{
queue<int> *tmp;
tmp = q1;
q1 = q2;
q2 = tmp;
}
void MyStack::push(int elememt)
{
q1->push(elememt);
}
int MyStack::pop()
{
if(q1->empty())
{
cout<<"栈已空"<<endl;
return -1;
}
rotation();
//cout<<q1->front()<<endl;
int ret = q1->front();
q1->pop();
swap();
return ret;
}
int MyStack::peek()
{
if(q1->empty())
{
cout<<"栈已空"<<endl;
return -1;
}
return q1->back();
}
int main()
{
MyStack stack1;
stack1.push(1);
stack1.push(2);
stack1.push(3);
stack1.push(4);
stack1.push(5);
for(int i=0;i<4;i++)
cout<<stack1.pop()<<endl;
cout<<stack1.peek()<<endl;
return 0;
}
C++只使用队列实现栈
最新推荐文章于 2024-04-28 18:45:35 发布