8.栈的最大值问题
问题的描述和思路可以参考这里
Java实现代码如下:
import java.util.Stack;
/**
* 栈的最大值问题 Title: Description: Company:
*
* @author 郑伟
* @date 2018年4月12日下午8:57:29
*/
public class SpecialStack {
Stack<Integer> stack = new Stack<>();
Stack<Integer> maxStack = new Stack<>();
public void push(Integer num) {
if (stack.isEmpty()) {
maxStack.push(num);
stack.push(num - maxStack.peek());
} else {
stack.push(num - maxStack.peek());
if (num > maxStack.peek()) {
maxStack.pop();
maxStack.push(num);
}
}
}
public int pop() {
if (!stack.isEmpty()) {
if (stack.peek() >= 0 && !maxStack.isEmpty()) {
int result = maxStack.pop();
maxStack.push(result - stack.pop());
return result;
} else if (stack.peek() < 0 && !maxStack.isEmpty()) {
return (maxStack.peek() + stack.pop());
} else {
return -1;
}
} else {
return -1;
}
}
public i