程式碼隨想錄:用佇列實現棧
class MyStack {
public:
//pop就是拿佇列的最後一個元素,只需要用另一個佇列對現有佇列遍歷,拿到最後一個元素即可
queue<int> target;
MyStack() {
}
void push(int x) {
target.push(x);
}
int pop() {
int len = target.size();
while(len>1){
target.push(target.front());
target.pop();
len--;
}
int val = target.front();
target.pop();
return val;
}
int top() {
int len = target.size();
while(len>1){
target.push(target.front());
target.pop();
len--;
}
int val = target.front();
target.push(target.front());
target.pop();
return val;
}
bool empty() {
return target.empty();
}
};
/**
* 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();
*/