用栈实现队列
Posted letlifestop
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用栈实现队列相关的知识,希望对你有一定的参考价值。
具体思路:
通过两个栈来模拟
class MyQueue public: /** Initialize your data structure here. */ stack<int>q1; stack<int>q2; MyQueue() /** Push element x to the back of queue. */ void push(int x) while(!q2.empty()) q1.push(q2.top()); q2.pop(); q1.push(x); while(!q1.empty()) q2.push(q1.top()); q1.pop(); return ; /** Removes the element from in front of queue and returns that element. */ int pop() int tmp = 0; if(!q2.empty()) tmp = q2.top(); q2.pop(); return tmp; /** Get the front element. */ int peek() int tmp = 0; if(!q2.empty()) tmp = q2.top(); return tmp; /** Returns whether the queue is empty. */ bool empty() return q2.empty(); ; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */
以上是关于用栈实现队列的主要内容,如果未能解决你的问题,请参考以下文章