|
使用二个栈来完成队列的功能,将栈1中元素全部取出放到栈2中,然后将新加的元素放到栈1中,再将栈2中所有元素依次放到栈1中。
class MyQueue {
public:
MyQueue() {
stack<int> s1;
stack<int> s2;
}
void push(int x) {
while(!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
s2.push(x);
while(!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
}
//取出队头 并返回值
int pop() {
int curr = s1.top();
s1.pop();
return curr;
}
//获得队头的值
int peek() {
return s1.top();
}
bool empty() {
return st.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
|