您的位置:首页 > 编程语言 > Java开发

包含min函数的栈java实现

2017-09-16 10:09 295 查看
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

import java.util.Stack;

public class Solution {

Stack<Integer> stack=new Stack<Integer>();
Stack<Integer> stack2=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=Integer.MAX_VALUE;
while(stack.isEmpty()!=true){
int node=stack.pop();
if(node<min){
min=node;
}
stack2.push(node);
}
while(stack2.isEmpty()!=true){
stack.push(stack2.pop());
}
return min;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息