Leetcode 232. 用栈实现队列 解题思路及C++实现
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 232. 用栈实现队列 解题思路及C++实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解題思路:
使用兩個棧,一個棧a用來存儲每一次操作得到的隊列,另一個棧b作為輔助棧。
- 在每一次push操作的時候,先把a中排好的隊列(先進先出),依次push進棧b,所以,棧b中元素的排序就是后進先出的棧順序;
- 然后把新的元素x push進棧b,整個棧b就是后進先出的棧順序;
- 然后再把b中的元素依次push進棧a,得到的棧a就是先進先出的隊列順序。
?
class MyQueue {stack<int> a, b; public:/** Initialize your data structure here. */MyQueue() {// nothing to do}/** Push element x to the back of queue. */void push(int x) {while(!a.empty()){b.push(a.top());a.pop();}b.push(x);while(!b.empty()){a.push(b.top());b.pop();}}/** Removes the element from in front of queue and returns that element. */int pop() {int num = a.top();a.pop();return num;}/** Get the front element. */int peek() {return a.top();}/** Returns whether the queue is empty. */bool empty() {return a.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();*/?
總結
以上是生活随笔為你收集整理的Leetcode 232. 用栈实现队列 解题思路及C++实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Receiver ED、Link qua
- 下一篇: 开启LeetCode之路