分享几道栈的oj题,利于进一步掌握stack的使用。
第一题题解
class MinStack {
public:
MinStack()
{
}
void push(int val)
{
ins.push(val);
if(mins.empty()||val<= mins.top())
{
mins.push(val);
}
}
void pop()
{
if(!mins.empty()&&ins.top() == mins.top())
{
mins.pop();
}
ins.pop();
}
int top()
{
return ins.top();
}
int getMin()
{
assert(!mins.empty());
return mins.top();
}
private:
stack<int> ins;
stack<int> mins;
};
第二题题解
class Solution {
public:
bool IsPopOrder(vector<int>& pushV, vector<int>& popV)
{
size_t pos2=0;
stack<int> ins;
for(const auto& e:pushV)
{
ins.push(e);
while(!ins.empty() && ins.top() == popV[pos2])
{
ins.pop();
++pos2;
}
}
return ins.empty() ;
}
};
第三题题解
class MyQueue {
public:
MyQueue() {
}
void push(int x)
{
while(!outs.empty())
{
int tmp = outs.top();
outs.pop();
ins.push(tmp);
}
ins.push(x);
}
int pop() {
while(!ins.empty())
{
int tmp =ins.top();
ins.pop();
outs.push(tmp);
}
int ret = outs.top();
outs.pop();
return ret;
}
int peek()
{
while(!ins.empty())
{
int tmp =ins.top();
ins.pop();
outs.push(tmp);
}
return outs.top();
}
bool empty()
{
return ins.empty()&&outs.empty();
}
private:
stack<int> ins;
stack<int> outs;
};
第四题题解
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> vv;
if(root == nullptr)
{
return vv;
}
int levelsize =1;//每层数据个数
q1.push(root);
while(!q1.empty())
{
vector<int> v;
while(levelsize--)//可以控制一层一层出数据
{
TreeNode* tmp =q1.front();
q1.pop();
v.push_back(tmp->val);
if(tmp->left)
{
q1.push(tmp->left);
}
if(tmp->right)
{
q1.push(tmp->right);
}
}
levelsize =q1.size();
//当前层出完了,将v插入vv
vv.push_back(v);
}
return vv;
}
queue<TreeNode*> q1;
};