leetcode232:两个堆栈实现队列
class MyQueue {
private:
stack<int> a;
stack<int> b;
public:
/** Initialize your data structure here. */
MyQueue():a(),b() {
}
/** Push element x to the back of queue. */
void push(int x) {
a.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(b.empty()){
while(!a.empty()){
b.push(a.top());
a.pop();
}
}
int temp=b.top();
b.pop();
return temp;
}
/** Get the front element. */
int peek() {
if(b.empty()){
while(!a.empty()){
b.push(a.top());
a.pop();
}
}
return b.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return b.empty() && a.empty();
}
};
leetcode225:两个队列实现堆栈
class MyStack {
private:
queue<int> a;
queue<int> b;
public:
/** Initialize your data structure here. */
MyStack():a(),b() {
}
/** Push element x onto stack. */
void push(int x) {
a.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int temp;
while(!a.empty()){
temp=a.front();
a.pop();
if(!a.empty())
b.push(temp);
}
while(!b.empty()){
a.push(b.front());
b.pop();
}
return temp;
}
/** Get the top element. */
int top() {
int temp;
while(!a.empty()){
temp=a.front();
a.pop();
b.push(temp);
}
while(!b.empty()){
a.push(b.front());
b.pop();
}
return temp;
}
/** Returns whether the stack is empty. */
bool empty() {
return a.empty()&&b.empty();
}
};