C++只使用队列实现栈

#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;
}

猜你喜欢

转载自blog.csdn.net/u014228447/article/details/80726274