最小栈
力扣简单习题:
代码实现
package com.immunize.leetcode.minstack;
import java.util.Stack;
/**
* 需求:实现栈的push top pop getMin方法。
*
* @author Mr IMMUNIZE
*
*/
public class MinStack {
// 构建一个栈对象来实现需求
private Stack<Integer> s = new Stack<Integer>();
// 该值为栈内的最小值
private int MinVal = Integer.MAX_VALUE;
// push方法
public boolean push(int x) {
// 如果压栈之前,栈为空,则先将第一个值赋值给MinVal
if (x <= MinVal) {
s.push(MinVal);
MinVal = x;
}
s.push(x);
return true;
}
// pop方法
public void pop() {
if (s.pop() == MinVal) {
MinVal = s.pop();
}
}
// top方法
public int top() {
return s.peek();
}
// getMin方法
public int getMin() {
return MinVal;
}
}
------------------------------------------------------------------------
package com.immunize.leetcode.minstack;
/**
* 测试最小栈
*
* @author Mr IMMUNIZE
*
*/
public class MinStackTest {
public static void main(String[] args) {
MinStack ms = new MinStack();
ms.push(-8);
ms.push(-3);
ms.push(8);
// ms.push(9);
ms.pop();
ms.push(5);
System.out.println(ms.getMin());
System.out.println(ms.top());
}
}
该实现是基于单栈的实现,相比于双栈实现来讲更加简洁。