版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37770023/article/details/81836677
算法刷题(26)_包含min函数的栈_学习记录
package p29;
import java.util.Stack;
/**
* 包含min函数的栈
* @author Guozhu Zhu
* @date 2018/8/19
* @version 1.0
*
*/
public class Test04 {
public Stack<Integer> data = new Stack<Integer>(); //存储数据的栈
public Stack<Integer> min = new Stack<Integer>(); //存储栈最小值的栈
public Integer temp; //存储栈最小值的临时标记元素
public void push(int node) {
if (temp != null) {
if (node < temp) {
temp = node;
min.push(temp);
}
data.push(node);
} else {
temp = node;
data.push(node);
min.push(node);
}
}
public void pop() {
int num1 = data.pop();
int num2 = min.pop();
//若两元素不等,则最小值还在数据栈中,所以还要push回去;
if (num1 != num2) {
min.push(num2);
}
}
public int top() {
return data.peek();
}
public int min() {
return min.peek();
}
public static void main(String[] args) {
Test04 minStack = new Test04();
minStack.push(1);
minStack.push(2);
minStack.push(3);
System.out.println(minStack.min());
}
}