[Day10] スタックとキュー、232 スタックを使用してキューを実装する、225 キューを使用してスタックを実装する
スタックとキュー
先入れ先出しスタック
先入れ先出しキュー
232 スタックによるキューの実現
トピックリンク: 232
スタックを使用してキューの出入りを模倣します。キューは先入れ先出しです。2 つのスタックを使用できます。1 つはスタッキング用、もう 1 つはスタッキング用です。スタッキングのスムーズさは、スタックの順序と一致します。スタックは最初に入力され、最後に出力されるため、スタックにプッシュされる要素が最初に入力され、次にスタックから出力されるように、別のスタックをポップアウトする必要があります。待ち行列が出ています。
データをプッシュする場合は、データが入力スタックに入れられていれば問題ありませんが、ポップする場合は操作が複雑になります。出力スタックが空の場合は、すべてのデータをスタックにインポートします(すべてのデータであることに注意してください)インポートされた)、出力からデータがスタックからポップされます。出力スタックが空でない場合は、データをスタックから直接ポップできます。
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stIn.push(x); //入栈
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
while(!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
/** Get the front element. */
int peek() {
int res = this->pop(); // 直接使用已有的pop函数
stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stIn.empty() && stOut.empty();
}
};
225 キューを使用したスタックの実装
トピックリンク: 225
2 つのキューを使用してスタックの出入りをシミュレートできます。スタックをシミュレートするためのキューの使用に重点が置かれています。
キューがスタックから要素をポップすることをシミュレートする場合、キューの先頭にある要素 (最後の要素を除く) をキューの最後尾に再追加するだけでよく、このとき要素をポップする順序は次のとおりです。スタック。
class MyStack {
public:
queue<int> que;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size = que.size();
size--;
while (size--) {
// 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
que.push(que.front());
que.pop();
}
int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了
que.pop();
return result;
}
/** Get the top element. */
int top() {
return que.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return que.empty();
}
};