一,原理:
将队列里数据状态转化成栈的状态。即在插入一个元素后,把前面所有元素弹出再插入。
二,代码展示
一代:
#include<iostream>
#include<queue>using namespace std;class Stack
{
private:void refresh(){int temp;int size = queue.size();for (int i = 0; i < size; i++){temp = queue.front();queue.pop();queue.push(temp);}}public:queue<int> queue;void insert(int x){queue.push(x);refresh();}void pop(){if (queue.empty()){cout << "the stack is empty !" << endl;return;}queue.pop();}int peak(){return queue.front();}bool empty(){return queue.empty();}};int main()
{Stack stack;for (int i = 1; i < 6; i++){stack.insert(i);cout << "the poped element is " << stack.peak() << endl;stack.pop();stack.pop();}return 0;}
插入函数有问题,应该在插入后将前面的n-1个元素颠倒到该元素后面。
void refresh()
{int temp;int size = queue.size();for (int i = 0; i < size - 1; i++){temp = queue.front();queue.pop();queue.push(temp);}
}
还有就是peak函数要提前判断栈是否为空,否则会出错。
int peak()
{if (queue.empty()){cout << "the stack is empty !" << endl;return -1;}return queue.front();
}