用队列实现栈
思路
栈是一种 后进先出(last in - first out, LIFO)的数据结构,栈内元素从顶端压入(push),从顶端弹出(pop)。一般我们用数组或者链表来实现栈,但是这篇文章会来介绍如何用队列来实现栈。队列是一种与栈相反的 先进先出(first in - first out, FIFO)的数据结构,队列中元素只能从 后端(rear)入队(push),然后从 前端(front)端出队(pop)。为了满足栈的特性,我们需要维护两个队列 q1 和 q2。同时,我们用一个额外的变量来保存栈顶元素。
算法
压入(push)
新元素永远从 q1 的后端入队,同时 q1 的后端也是栈的 栈顶(top)元素。

使用队列实现栈的下列操作:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
class MyStack { public: //单链表实现 /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { int size = q.size(); q.push(x); int tmp; for(int i = 0; i < size; i++){ q.push(q.front()); q.pop(); } } /** Removes the element on top of the stack and returns that element. */ int pop() { int tmp = q.front(); q.pop(); return tmp; } /** Get the top element. */ int top() { return q.front(); } /** Returns whether the stack is empty. */ bool empty() { return q.empty(); } private: queue<int> q; };
class MyStack { //双队列实现栈 public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { pushQueue.push(x); topValue = x; } /** Removes the element on top of the stack and returns that element. */ int pop() { while(pushQueue.size()>1){ topValue = pushQueue.front(); popQueue.push(topValue); pushQueue.pop(); } int result = pushQueue.front(); pushQueue.pop(); queue<int> tmp = pushQueue; pushQueue = popQueue; popQueue = tmp; return result; } /** Get the top element. */ int top() { return topValue; } /** Returns whether the stack is empty. */ bool empty() { return pushQueue.empty(); } private: queue<int> pushQueue; queue<int> popQueue; int topValue; };
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

浙公网安备 33010602011771号