一昵慌、題目描述
題目描述
二已卷、思路
聲明兩個隊列解決:
queue<int> q1用于存儲元素侧蘸;
queue<int> q2用于輔助操作鹉梨。
push()方法實現(xiàn):
直接將元素存入q1俯画。
top()、pop()方法實現(xiàn):
先將q1除了隊尾元素外的所有元素全部存入q2泡仗;
q1只剩隊尾元素娩怎,即:棧頂元素截亦,操作柬讨;
將q2的元素依次彈出全部存入q1崩瓤。
empty()方法實現(xiàn):
直接檢查q1是否為空即可。
三踩官、代碼
class MyStack {
public:
queue<int> q1; // 用于存儲
queue<int> q2; // 用于輔助
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
while(q1.size() > 1){
int cur = q1.front();
q2.push(cur);
q1.pop();
}
// 此時q1還剩隊尾元素
int res = q1.front();
q1.pop();
while(q2.size() != 0){
int cur = q2.front();
q1.push(cur);
q2.pop();
}
return res;
}
/** Get the top element. */
int top() {
while(q1.size() > 1){
int cur = q1.front();
q2.push(cur);
q1.pop();
}
// 此時q1還剩隊尾元素
int res = q1.front();
q2.push(res);
q1.pop();
while(q2.size() != 0){
int cur = q2.front();
q1.push(cur);
q2.pop();
}
return res;
}
/** Returns whether the stack is empty. */
bool empty() {
if(q1.size() == 0)
return true;
return false;
}
};
/**
* 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();
*/
四却桶、提交結(jié)果
提交結(jié)果