leetcodeはキューでスタックc++を実現する
1345 ワード
キューによるスタックの実装
キューを使用してスタックを実装するには、次の手順に従います.
push(x)–要素xスタックpop()–スタックトップ要素top()の除去–スタックトップ要素empty()の取得–スタックが空であるかどうかを返す
解:スタックを2つのキューで実装
stlでのキューの使用:
キューを使用してスタックを実装するには、次の手順に従います.
push(x)–要素xスタックpop()–スタックトップ要素top()の除去–スタックトップ要素empty()の取得–スタックが空であるかどうかを返す
解:スタックを2つのキューで実装
stlでのキューの使用:
#include//
queue q; // ,
q.empty()// true, false
q.size() //
q.pop() //
q.front() // ,
q.push(X) // ,X
q.back() // ,
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
input.push(x);
q2q(output,input);
std::swap(input,output);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int res=output.front();
output.pop();
return res;
}
/** Get the top element. */
int top() {
return output.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return output.empty();
}
private:
queue input;
queue output;
void q2q(queue &a,queue&b)
{
while(!a.empty())
{
b.push(a.front());
a.pop();
}
}
};