2つのスタックシミュレーションキュー、2つのキューシミュレーションスタック
2つのスタックシミュレーションキューエンキュー:要素をスタックAにエンキューします. デキュー:スタックBが空であるかどうかを判断し、空である場合、スタックAのすべての要素popをスタックBにpushし、スタックBをスタックBに出力する.空でない場合、スタックBは直接スタックを出ます.
C/C++コード
2つのキューシミュレーションスタックインスタック:要素をキューAに入れます. スタック:キューAの要素の個数が1であるかどうかを判断し、1に等しい場合、キューを出ます.そうでない場合、キューAの要素をキューから出してキューBに入れます.キューAの要素が1つ残るまで、キューAが出て、キューBの要素をキューAに入れます.
C/C++コード
C/C++コード
class Solution
{
public:
void push(int node) { //
stack1.push(node);
}
int pop() { //
int a;
if(stack2.empty()){
while(!stack1.empty()){
a = stack1.top();
stack2.push(a);
stack1.pop();
}
}
a = stack2.top();
stack2.pop();
return a;
}
private:
stack<int> stack1;
stack<int> stack2;
};
2つのキューシミュレーションスタック
C/C++コード
class Solution
{
public:
void push(int node) { //
queue1.push(node);
}
int pop() { //
int a, b;
int size1 = queue1.size();
if(1 == size1){
a = queue1.front();
queue1.pop();
}
else{
while(!queue1.empty()){
b = queue1.front();
queue2.push(b);
queue1.pop();
if(queue1.size()==1)
break;
}
a = queue1.front();
queue1.pop();
while(!queue2.empty()){
b = queue2.front();
queue1.push(b);
queue2.pop();
}
}
return a;
}
private:
queue<int> queue1;
queue<int> queue2;
};