leetcode-232 用栈实现队列
生活随笔
收集整理的這篇文章主要介紹了
leetcode-232 用栈实现队列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用棧實現隊列的下列操作:
- push(x) – 將一個元素放入隊列的尾部。
- pop() – 從隊列首部移除元素。
- peek() – 返回隊列首部的元素。
- empty() – 返回隊列是否為空
棧的特點:后入先出
隊列的特點:先入先出
使用一個數據棧,一個輔助棧,我們最終的目的是想要將新添加的元素放入棧低,所以使用輔助棧先將之前的數據棧元素保存起來,將新元素放入空的數據棧,再將輔助棧中的元素重新添加到數據棧中即可。
實現如下:
class MyQueue {
private:stack<int> S;
public:/** Initialize your data structure here. */MyQueue() {}/** Push element x to the back of queue. */void push(int x) {stack<int> tmp;while(!S.empty()){tmp.push(S.top());S.pop();}S.push(x);while(!tmp.empty()) {S.push(tmp.top());tmp.pop();}}/** Removes the element from in front of queue and returns that element. */int pop() {int tmp = S.top();S.pop();return tmp;}/** Get the front element. */int peek() {return S.top();}/** Returns whether the queue is empty. */bool empty() {return S.empty();}
};
總結
以上是生活随笔為你收集整理的leetcode-232 用栈实现队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 那么那么歌词是哪首歌啊?
- 下一篇: leetcode-155 最小栈