代码
public class Node
{
public int Value;
public Node Next;
public Node(int x,Node next)
{
Value=x;
Next=next;
}
}
public class MinStack {
/** initialize your data structure here. */
public Node StackTop;
public MinStack() {
StackTop=null;
}
public void Push(int x) {
if(StackTop==null)
StackTop=new Node(x,null);
else
{
StackTop=new Node(x,StackTop);
}
}
public void Pop() {
StackTop=StackTop.Next;
}
public int Top() {
return StackTop.Value;
}
public int GetMin() {
Node head=StackTop;
int min=StackTop.Value;
while(head.Next!=null)
{
if(min>head.Next.Value)
min=head.Next.Value;
head=head.Next;
}
return min;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.Push(x);
* obj.Pop();
* int param_3 = obj.Top();
* int param_4 = obj.GetMin();
*/
思路
实现的栈为链栈
getmin函数中有min 循环检测中遇到比min小的数就赋值给min