Leetcode255用队列构造栈
生活随笔
收集整理的這篇文章主要介紹了
Leetcode255用队列构造栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用隊列構造棧
題目鏈接:Leetcode225
使用隊列實現棧的下列操作:
注意:
你只能使用隊列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。 你所使用的語言也許不支持隊列。 你可以使用 list 或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。 你可以假設所有操作都是有效的(例如, 對一個空的棧不會調用 pop 或者 top 操作)。解題思路:
push(x)操作要點: 隊列先進先出,模擬棧后進先出。
leetcode提交代碼如下:
class MyStack { public:/** Initialize your data structure here. */std::queue<int> _data;MyStack() {}/** Push element x onto stack. */void push(int x) {std::queue<int> temp_queue;//臨時隊列temp_queue.push(x);//新元素x放入臨時隊列while(!_data.empty())//原隊列進臨時隊列{temp_queue.push(_data.front());//放入臨時隊列_data.pop();//從原隊列出隊}while(!temp_queue.empty())//臨時隊列回到原隊列_data{_data.push(temp_queue.front());temp_queue.pop();//臨時隊列釋放}}/** Removes the element on top of the stack and returns that element. */int pop() {int x=_data.front();_data.pop();return x;}/** Get the top element. */int top() {return _data.front();}/** Returns whether the stack is empty. */bool empty() {return _data.empty();} };/*** Your MyStack object will be instantiated and called as such:* MyStack* obj = new MyStack();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->top();* bool param_4 = obj->empty();*/總結
以上是生活随笔為你收集整理的Leetcode255用队列构造栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 递归构造二叉树和二叉树的遍历
- 下一篇: 宇宙大爆炸,之前的星球与王子遭到月球撞击