public class Code2_Stack_Min {
public Stack
<Integer> mainStack
= new Stack<>();
public Stack
<Integer> minStack
= new Stack<>();
public void push(int data
){
mainStack
.push(data
);
if(minStack
.isEmpty() || data
<= minStack
.peek()){
minStack
.push(data
);
}
}
public Integer
pop() throws Exception
{
if (mainStack
.isEmpty()){
throw new Exception("stack is empty");
}
if(mainStack
.peek().equals(minStack
.peek())){
minStack
.pop();
}
return mainStack
.pop();
}
public Integer
getMin() throws Exception
{
if(minStack
.isEmpty()){
throw new Exception("stack is empty");
}
return minStack
.peek();
}
public static void main(String
[] args
) throws Exception
{
Code3_Stack_Min stack_min
= new Code3_Stack_Min();
stack_min
.push(4);
stack_min
.push(4);
stack_min
.push(9);
stack_min
.push(3);
stack_min
.push(7);
stack_min
.push(2);
System
.out
.println(stack_min
.minStack
.peek());
System
.out
.println("=======================");
System
.out
.println(stack_min
.pop());
System
.out
.println(stack_min
.pop());
System
.out
.println(stack_min
.pop());
System
.out
.println("=======================");
System
.out
.println(stack_min
.minStack
.peek());
}
}
2
=======================
2
7
3
=======================
4
转载请注明原文地址: https://yun.8miu.com/read-20230.html