您的位置:首页 > Web前端

剑指offer:包含min函数的栈

2017-08-04 22:37 211 查看
题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息