您的位置:首页 > 其它

包含min函数的栈

2016-04-08 00:21 323 查看
题目描述

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

import java.util.Stack;

public class Solution {

private Stack<Integer> stackData;
private Stack<Integer> stackMin;

public Solution(){
stackData = new Stack<Integer>();
stackMin = new Stack<Integer>();
}

public void push(int node) {
if(stackMin.isEmpty()){
stackMin.push(node);
}else{
if(node <= this.min()){
stackMin.push(node);
}
}
stackData.push(node);
}

public void pop() {
if(stackData.isEmpty()){
//   throws new RuntimeException("Your stack is empty");
}
int value = this.stackData.pop();
if(value == this.min()){
stackMin.pop();
}
}

public int top() {
if(stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty.");
}
return stackMin.peek();
}

public int min() {
if(stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty.");
}
return stackMin.peek();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: