题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
题目解答
import java.util.Stack; public class Solution { private Stack<Integer> stackData=new Stack<>(); private Stack<Integer> stackMin=new Stack<>(); public void push(int node) { if(stackMin.isEmpty()){ stackMin.push(node); }else if(node<min()){ stackMin.push(node); } stackData.push(node); } public void pop() { if(stackData.isEmpty()){ throw new RuntimeException("the stack is empty"); } int value=stackData.pop(); if(value==min()){ stackMin.pop(); } } public int top() { if(stackData.isEmpty()){ throw new RuntimeException("the stack is empty"); } return stackData.peek(); } public int min() { if(stackMin.isEmpty()){ throw new RuntimeException("the stack is empty"); } return stackMin.peek(); } }
原文地址:https://www.cnblogs.com/chanaichao/p/10158793.html
时间: 2024-10-09 03:47:33