タイトルの説明:
キューを使用して、スタックの次の操作を実装します。
- push(x)–要素xをスタックにプッシュします
- pop()–スタックの一番上の要素を削除する
- top()-スタックの一番上の要素を取得
- empty()–スタックが空かどうかを返します
注:
キューの基本操作のみを使用できます。つまり、プッシュトゥバック、フロントからのピーク/ポップ、サイズ、空の操作は正当です。
言語がキューをサポートしていない可能性があります。標準のキュー操作であれば、listまたはdeque(両端キュー)を使用してキューをシミュレートできます。
すべての操作が有効であると想定できます(たとえば、popまたはtop操作は空のスタックで呼び出されません)。
回答コード:
class MyStack {
queue<int> q1;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
//力扣模版需要返回值进行检测
//int pop() {
void pop(){
queue<int> q2;
while (q1.size() > 1)
{
q2.push(q1.front());
q1.pop();
}
//int tmp = q1.front();
q1.pop();
q1 = q2;
//return tmp;
}
/** Get the top element. */
int top() {
queue<int> q2;
while (q1.size() > 1)
{
q2.push(q1.front());
q1.pop();
}
int tmp = q1.front();
q2.push(q1.front());
q1 = q2;
return tmp;
}
/** Returns whether the stack is empty. */
bool empty() {
return q1.empty();
}
};
異なる意見がある場合は、メッセージを残して訪問してください!!!