定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

    xiaoxiao2021-03-25  103

    如题,定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。 大致思路就是再定义一个栈,如果碰到比当前暂存的小的 就放到栈中,min的时候就出这个栈栈顶的

    import java.util.Stack; public class Solution { Stack<Integer> stack = new Stack<Integer>(); Stack<Integer> stackmin = new Stack<Integer>(); Integer num =null; public void push(int node){ if(num==null){ num = node; stack.push(node); stackmin.push(num); }else{ if(node<num) { num = node; stackmin.push(num); } stack.push(node); } } public void pop(){ int num = stack.pop(); int num2 = stackmin.pop(); if(num!=num2){ stackmin.push(num2); } } public int top(){ int top = stack.pop(); stack.push(top); return top; } public int min(){ int top = stackmin.pop(); stackmin.push(top); return top; } }
    转载请注明原文地址: https://ju.6miu.com/read-9620.html

    最新回复(0)