leetcode-225 队列实现栈
生活随笔
收集整理的這篇文章主要介紹了
leetcode-225 队列实现栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用隊列實現棧的下列操作:
- push(x) – 元素 x 入棧
- pop() – 移除棧頂元素
- top() – 獲取棧頂元素
- empty() – 返回棧是否為空
隊列的特點:先入先出
棧的特點:后入先出
即我們每次添加元素到隊列時,想要達到棧的效果,則需要調整當前元素到隊列頭部
方法一:雙隊列
一個臨時隊列保存push進去的元素,將數據隊列元素按序添加到臨時隊列,再將臨時隊列所有元素按序添加到數據隊列
class MyStack {
private:queue<int> data;
public:/** Initialize your data structure here. */MyStack() { }/** Push element x onto stack. */void push(int x) {queue<int> tmp;tmp.push(x);while(!data.empty()) {tmp.push(data.front());data.pop();}while(!tmp.empty()) {data.push(tmp.front());tmp.pop();}}/** Removes the element on top of the stack and returns that element. */int pop() {int tmp = data.front();data.pop();return tmp;}/** Get the top element. */int top() {return data.front();}/** Returns whether the stack is empty. */bool empty() {return data.empty();}
}
方法二:不需要臨時隊列
添加一個新的元素時將該元素之前的元素彈出,再添加到隊列,即可達到調整新元素位置到隊頭的目的
不需要額外的存儲空間
class MyStack {
private:queue<int> data;
public:/** Initialize your data structure here. */MyStack() { }/** Push element x onto stack. */void push(int x) {int size = data.size();data.push(x);while(size) {data.push(data.front());data.pop();size --;}}/** Removes the element on top of the stack and returns that element. */int pop() {int tmp = data.front();data.pop();return tmp;}/** Get the top element. */int top() {return data.front();}/** Returns whether the stack is empty. */bool empty() {return data.empty();}
};
總結
以上是生活随笔為你收集整理的leetcode-225 队列实现栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一吨木头能烧多少㎏木炭:
- 下一篇: 那么那么歌词是哪首歌啊?