Java實現最小棧
阿新 • • 發佈:2018-12-26
思路:
使用2個棧,其中一個棧作為普通棧使用,另一個只把最小的元素入棧。
入棧:如果元素小於或等於最小元素棧頂,則入最小元素棧
出棧:如果元素等於最小元素棧頂,則最小元素出棧
Code:
class MinStack { private Stack<Integer> innerStack; private Stack<Integer> minStack; /** initialize your data structure here. */ public MinStack() { innerStack = new Stack<Integer>(); minStack = new Stack<Integer>(); } public void push(int x) { innerStack.push(x); //add to queue if (minStack.isEmpty() || x <= minStack.peek()) { minStack.push(x); } } public Integer pop() { if (!innerStack.empty()) { Integer peek = innerStack.pop(); if (peek.equals(minStack.peek())) { minStack.pop(); } return peek; } return null; } public Integer top() { if (!innerStack.empty()) { return innerStack.peek(); } return null; } public Integer getMin() { if (!minStack.empty()) { return minStack.peek(); } return null; } }