Leetcode232使用栈实现队列
生活随笔
收集整理的這篇文章主要介紹了
Leetcode232使用栈实现队列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:使用棧實現隊列。
使用棧實現隊列的下列操作:
示例:
MyQueue queue = new MyQueue();queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false說明:
你只能使用標準的棧操作 – 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的語言也許不支持棧。你可以使用 list 或者 deque(雙端隊列)來模擬一個棧,只要是標準的棧操作即可。
假設所有操作都是有效的 (例如,一個空的隊列不會調用 pop 或者 peek 操作)。
來源:力扣(LeetCode)
鏈接:232使用棧實現隊列
解題思路:
核心:使用棧后進先出,模擬隊列的先進先出。
Leetcode提交代碼:
class MyQueue { public:/** Initialize your data structure here. */std::stack<int> _data;MyQueue() {}/** Push element x to the back of queue. */void push(int x) {std::stack<int> temp_stack;//臨時堆棧//if(_data.empty())//不需要這步判斷是否為空// _data.push(x);while(!_data.empty())//原堆棧數據進入臨時堆棧{temp_stack.push(_data.top());_data.pop();}temp_stack.push(x);//新來的元素進入臨時堆棧while(!temp_stack.empty())//臨時堆棧數據交給原堆棧{_data.push(temp_stack.top());temp_stack.pop();}}/** Removes the element from in front of queue and returns that element. */int pop() {//這里需要注意,返回的是一個數值int x=_data.top();//_data.pop();return x;}/** Get the front element. */int peek() {return _data.top();}/** Returns whether the queue is empty. */bool empty() {return _data.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();*/總結:
這里需要總結的是pop()函數的書寫
起初寫成:理解錯了題意,正確應該如下:pop()返回的是被出棧的那個數據。
正確的pop()
int pop() { int x=_data.top();_data.pop();return x;//返回被彈出的數據 }總結
以上是生活随笔為你收集整理的Leetcode232使用栈实现队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 宇宙大爆炸,之前的星球与王子遭到月球撞击
- 下一篇: Leetcode155最小栈