左程云面试算法学习——1.使用双栈(stack),获取当前序列最小值

import java.util.Stack;


public class Pro_1_GetMinStack {


//stackData :当前序列入栈
private Stack<Integer> stackData;
//stackMin : 栈顶为当前序列的最小
private Stack<Integer> stackMin;

public Pro_1_GetMinStack()
{
stackData = new Stack<>();
stackMin = new Stack<>();
}
/*
* 对数num
* stackData 正常入栈 push(num)
* 
* stackMin 为空 则 push(num);
* 非空 则将stackMIn 栈顶与num比较,num更小则入stackMin栈,否则不处理
* 
* */
public void push(int num)
{
if(stackMin.isEmpty())
{
stackMin.push(num);
}
else if(num<=stackMin.peek())
{
stackMin.push(num);
}
stackData.push(num);
}

/*
* 出栈stackData,为空则报异常
* 否则正常出栈,值保存为value
* 
* stackMin栈顶与value比较,只有相等和小于value两种情况,等于时,出栈;
* 否则不处理
* 
* 如何进栈,就如何出栈
* */
public int pop()
{
if(stackData.isEmpty())
{
throw new RuntimeException("your stack is empty.");
}
int value = stackData.pop();
if(value==stackMin.peek())
{
stackMin.pop();
}
return value;
}

//获取stackMin的栈顶,注意为空时,抛异常
public int getmin()
{
if(stackMin.isEmpty())
{
throw new RuntimeException("your stack is empty.");
}
return stackMin.peek();
}

//test 
public static void main(String[] args) {
// TODO Auto-generated method stub
Pro_1_GetMinStack stack1=new Pro_1_GetMinStack();


stack1.push(3);
System.out.println(stack1.getmin());
stack1.push(4);
System.out.println(stack1.getmin());
stack1.push(1);
System.out.println(stack1.getmin());
System.out.println(stack1.pop());
System.out.println(stack1.getmin());
}
}
//会继续归纳和总结


你可能感兴趣的:(算法,面试,栈,stack)