Description
Implement the following operations of a stack using queues.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
empty() – Return whether the stack is empty.
Notes:
You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
My solution
采用两个queue, 修改pop, 一次AC
class MyStack {
private:
queue<int> upper, lower,temp;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
upper.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int nsize = upper.size();
for (int i = 0; i < nsize - 1; i++) {
int val = upper.front();
upper.pop();
lower.push(val);
}
int r = upper.front();
upper.pop();
temp = upper;
upper = lower;
lower = temp;
return r;
}
/** Get the top element. */
int top() {
return upper.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return upper.empty();
}
};
Discuss
class Stack {
public:
queue<int> que;
// Push element x onto stack.
void push(int x) {
que.push(x);
for(int i=0;i<que.size()-1;++i){
que.push(que.front());
que.pop();
}
}
// Removes the element on top of the stack.
void pop() {
que.pop();
}
// Get the top element.
int top() {
return que.front();
}
// Return whether the stack is empty.
bool empty() {
return que.empty();
}
};
上述代码采用一个queue, 修改push; 基本原理就是在添入的时候, 把其他的元素移动一次. 这种思路更清晰.
————————— 2017.08.12 补充 ———————————–
leetcode 232 类似, 要求利用stack来模拟queue(总感觉前面做过呢…).
思路类似, 再存储数据的时候, 就把它们按照queue应该有的顺序调整好, 只修改push !!!
//
// Created by Fennnnng on 2017/8/12.
//
# include<stack>
using namespace std;
class MyQueue {
private:
stack<int> s1, s2;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
int toptemp;
while (!s1.empty()) {
toptemp = s1.top();
s2.push(toptemp);
s1.pop();
}
s1.push(x);
while (!s2.empty()) {
toptemp = s2.top();
s1.push(toptemp);
s2.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int toptemp = s1.top();
s1.pop();
return toptemp;
}
/** Get the front element. */
int peek() {
return s1.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.empty();
}
};