剑指offer:包含min函数的栈

xiaoxiao2021-02-27  236

题目描述

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

转载请注明原文地址: https://www.6miu.com/read-8944.html

最新回复(0)