定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。
import java.util.Stack; public class Solution { Stack<Integer> dataStack = new Stack<Integer>(); Stack<Integer> minStack = new Stack<Integer>(); public void push(int node) { Integer temp = new Integer(node); dataStack.push(temp); if (minStack.empty()) { minStack.push(temp); } else { int min = minStack.peek().intValue(); if (node > min) { minStack.push(minStack.peek()); } else { minStack.push(temp); } } } public void pop() { dataStack.pop(); minStack.pop(); } public int top() { return dataStack.peek(); } public int min() { return minStack.peek(); } }
时间: 2024-12-13 16:40:13