アルゴリズム入門:キュー実装スタック、スタック実装キュー
2125 ワード
leetcode 232:2つのスタック実装キュー
class MyQueue {
private:
stack a;
stack 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();
}
};
leetcode 225:2つのキュー実装スタック
class MyStack {
private:
queue a;
queue 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();
}
};