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

来源:互联网 发布:单片机是嵌入式处理器 编辑:程序博客网 时间:2024/06/10 05:52

如题,定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的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; } }
0 0