題目來源
使用隊列來實現(xiàn)棧,我一開始先入為主的想法就是用兩個隊列來實現(xiàn),push進一個,就把這個元素push進一個空隊列,然后把另一個隊列的元素一次出對再入剛push進一個元素的隊列。還得判斷一下當前哪個隊列為空,冗長又復雜。
代碼如下:
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
cur = 1;
}
/** Push element x onto stack. */
void push(int x) {
if (cur == 1) {
q1.push(x);
while (!q2.empty()) {
int tmp = q2.front();
q2.pop();
q1.push(tmp);
}
cur = 2;
}
else {
q2.push(x);
while (!q1.empty()) {
int tmp = q1.front();
q1.pop();
q2.push(tmp);
}
cur = 1;
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
if (cur == 1 && !q2.empty()) {
int tmp = q2.front();
q2.pop();
return tmp;
}
if (cur == 2 && !q1.empty()) {
int tmp = q1.front();
q1.pop();
return tmp;
}
return 0;
}
/** Get the top element. */
int top() {
if (cur == 1 && !q2.empty()) {
return q2.front();
}
if (cur == 2 && !q1.empty()) {
return q1.front();
}
return 0;
}
/** Returns whether the stack is empty. */
bool empty() {
if (q1.empty() && q2.empty())
return true;
return false;
}
private:
int cur;
queue<int> q1;
queue<int> q2;
};
/**
* 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();
*/
然后實際上一個隊列就可以了,每次push的時候先push,然后把之前的出隊列再入隊列。代碼如下:
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<q.size()-1; i++) {
int tmp = q.front();
q.pop();
q.push(tmp);
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int tmp = q.front();
q.pop();
return tmp;
}
/** Get the top element. */
int top() {
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
private:
int cur;
queue<int> q;
};
/**
* 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();
*/