方法1:
连着232. Implement Queue using Stacks, 结果反而花更久时间。。不能直接套用过来。这道题里最后采用了:push只管push就行,popStack每次倒灌过来取出top/pop之后负责再灌回去,包揽所有清理工作。
这样push是O(1), pop/top 都是O(n).
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
pushQueue.push(x);
return;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int N = pushQueue.size();
for(int i = 0; i < N - 1; i++) {
popQueue.push(pushQueue.front());
pushQueue.pop();
}
int t = pushQueue.front();
pushQueue.pop();
while (!popQueue.empty()){
pushQueue.push(popQueue.front());
popQueue.pop();
}
return t;
}
/** Get the top element. */
int top() {
int N = pushQueue.size();
for(int i = 0; i < N - 1; i++) {
popQueue.push(pushQueue.front());
pushQueue.pop();
}
int t = pushQueue.front();
popQueue.push(t);
pushQueue.pop();
while (!popQueue.empty()){
pushQueue.push(popQueue.front());
popQueue.pop();
}
return t;
}
/** Returns whether the stack is empty. */
bool empty() {
return popQueue.empty() && pushQueue.empty();
}
private:
queue<int> popQueue, pushQueue;
};
/**
* 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();
*/
方法2:
grandyang: http://www.cnblogs.com/grandyang/p/4568796.html
参照了grandyang的写法:第一个栈q1正常储存,第二个栈q2永远keep<=1 个元素,每次新进来x会把上一次的top推进q1。如果连续pop,则通过平移的方法再取出上一个top(q1中队尾的元素)。
这种方法push O(1), top O(1), pop O(1), 只有连续pop是O(n)。
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {}
/** Push element x onto stack. */
void push(int x) {
q2.push(x);
while (q2.size() > 1) {
q1.push(q2.front()); q2.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int x = top(); q2.pop();
return x;
}
/** Get the top element. */
int top() {
if (q2.empty()) {
for (int i = 0; i < (int)q1.size() - 1; ++i) {
q1.push(q1.front()); q1.pop();
}
q2.push(q1.front()); q1.pop();
}
return q2.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q1.empty() && q2.empty();
}
private:
queue<int> q1, q2;
};
方法3:
grandyang: http://www.cnblogs.com/grandyang/p/4568796.html
grandyang的写法,只需要在push的时候manipulate就行了,而且只用到一个queue。原理是每次入队完全模拟stack的方式:x加入队尾,前面的所有元素依次全部出队再入队,x就变成了top。
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
for (int i = 0; i < (int)q.size() - 1; ++i) {
q.push(q.front()); q.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int x = q.front(); q.pop();
return x;
}
/** Get the top element. */
int top() {
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
private:
queue<int> q;
};