LeetCode Min Stack 最小值栈

时间:2023-03-09 06:04:07
LeetCode Min Stack 最小值栈

题意:实现栈的四个基本功能。要求:在get最小元素值时,复杂度O(1)。

思路:链表直接实现。最快竟然还要61ms,醉了。

 class MinStack {
public:
MinStack(){
head.next=;
head.t=;
m=0x7FFFFFFF;
}
void push(int x) {
node *p=(node *)new(node);
p->t=x;
p->next=head.next;
head.next=p;
head.t++;
if(x < m) //要更新
m = x;
} void pop() { if(==head.t) return ;
else if(head.t)
{
head.t--;
if(head.next->t==m) //刚好等于最小值m,要更新最小值
{
int sma=0x7FFFFFFF;
node *p=head.next->next;
while( p )
{
if(p->t<sma)
sma=p->t;
p=p->next;
}
m=sma;
}
head.next=head.next->next;
}
} int top() {
if(head.t)
return head.next->t;
return ;
} int getMin() {
return m;
}
private:
struct node
{
int t;
node *next;
};
node head;
int m;
};