剑指offer:包含min函数的栈

来源:互联网 发布:手机淘宝2015旧版本5.5 编辑:程序博客网 时间:2024/06/12 06:25

题目描述

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

方法1:在top中写

这个题目挺无聊的,将查找最小值的实现放在top中写也可以通过测试用例。
【运行时间:16ms  占用内存:8272k】
import java.util.*;public class Solution {    Stack<Integer> stack=new Stack<Integer>();    public void push(int node) {        stack.push(node);    }    public void pop() {        stack.pop();    }        public int top() {        int min=stack.peek();        int temp=0;        for(Iterator<Integer> it=stack.iterator();it.hasNext();){        temp=it.next();        if(temp<min){        min=temp;        }        }        return min;    }    public int min() {        return top();    }}

方法2:正常

【运行时间:17ms  占用内存:8264k】

若果在top()中使用stack.pop()操作来提取元素会报错:java.util.EmptyStackException。因为主函数要执行peek()操作,所以不能随便出栈,不能让栈空。
import java.util.*;public class Solution {    Stack<Integer> stack=new Stack<Integer>();    public void push(int node) {        stack.push(node);    }        public void pop() {        stack.pop();    }        public int top() {        return stack.peek();    }        public int min() {        int min=stack.peek();        int temp=min;        Iterator<Integer> it=stack.iterator();        while(it.hasNext()){           temp=it.next();           if(temp<min)             min=temp;        }        return min;    }}



原创粉丝点击