左程雲面接アルゴリズム学習——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());
}
}
//