题解 | #包含min函数的栈#
包含min函数的栈
https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
class Solution {
public:
int *base=new int[300]; //栈底指针
int *top1=base; //栈顶指针,切记要进行初始化
stack<int> sta;
void push(int value) {
if (this->top1-this->base == 300) //栈满
{
return;
}
if(this->top1==this->base)
{
*(this->top1++) = value;
sta.push(value);
}
*(this->top1++) = value; //元素e压入栈顶,然后栈顶指针加1,等价于*S.top=e; S.top++;
sta.push(this->top()>sta.top()?sta.top():this->top() );
}
void pop() {
if(this->top1==this->base)
{
return;
}
else
{
this->top1--;
sta.pop();
}
}
int top() {
if(this->top1==this->base)
{
return 0;
}
else{
return *(this->top1-1);
}
}
int min() {
return sta.top();
}
};
查看6道真题和解析