class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stack<int>s2;
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
s1.push(x);
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int x=s1.top();
s1.pop();
return x;
}
/** Get the front element. */
int peek() {
return s1.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.empty();
}
private:
stack<int>s1;
};
上面那个解法虽然简单,但是效率不高,因为每次在push的时候,都要翻转两边栈,下面这个方法使用了两个栈_new和_old,其中新进栈的都先缓存在_new中,入股要pop和peek的时候,才将_new中所有元素移到_old中操作,提高了效率。
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s2.push(x);
}
void shiftStack(){
if(s1.empty()){
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
shiftStack();
int x=s1.top();
s1.pop();
return x;
}
/** Get the front element. */
int peek() {
shiftStack();
return s1.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.empty()&&s2.empty();
}
private:
stack<int>s1,s2;
};