《剑指offer》包含min函数的栈

来源:互联网 发布:linux jdk6安装教程 编辑:程序博客网 时间:2024/06/09 14:14

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

解析:直接利用java.util.Stack包里的Stack辅助实现该题目,需要注意的是在求min的时候,需要维护原始栈的数据以及顺序,这里使用list维护。

代码如下:

import java.util.*;public class Solution {    Stack<Integer> stack = new Stack<>();    public void push(int node) {        stack.push(node);    }    public void pop() {        stack.pop();    }    public int top() {        return stack.peek();    }    public int min() {        int min=top();        List<Integer> list = new ArrayList<>();        while (!stack.isEmpty()){            int temp=top();            list.add(temp);            if(temp<min){                min=temp;            }            pop();        }        Collections.reverse(list);        stack.addAll(list);        return min;    }}
原创粉丝点击