面试题21:包含min函数的栈
2017-02-13 21:29
176 查看
面试题21:包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
代码:
package offer;
import java.util.Stack;
/**
* 面试题21:包含min函数的栈
* 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
*/
public class _21_min_stack {
public static void main(String[] args){
}
}
/**
* pop取出并删除
* peek取出不删除
*/
class Solution21 {
Stack<Integer> s1=new Stack<Integer>();//数据栈
Stack<Integer> s2=new Stack<Integer>();//辅助栈
public void push(int node) {
s1.push(node);
if(s2.empty()){
s2.push(node);
}else{
int tmp=s2.peek();
if(tmp>=node){
s2.push(node);
}else{
s2.push(tmp);
}
}
}
public void pop() {
s1.pop();
s2.pop();
}
public int top() {
return s1.peek();
}
public int min() {
return s2.peek();
}
}
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。代码:
package offer;
import java.util.Stack;
/**
* 面试题21:包含min函数的栈
* 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
*/
public class _21_min_stack {
public static void main(String[] args){
}
}
/**
* pop取出并删除
* peek取出不删除
*/
class Solution21 {
Stack<Integer> s1=new Stack<Integer>();//数据栈
Stack<Integer> s2=new Stack<Integer>();//辅助栈
public void push(int node) {
s1.push(node);
if(s2.empty()){
s2.push(node);
}else{
int tmp=s2.peek();
if(tmp>=node){
s2.push(node);
}else{
s2.push(tmp);
}
}
}
public void pop() {
s1.pop();
s2.pop();
}
public int top() {
return s1.peek();
}
public int min() {
return s2.peek();
}
}
相关文章推荐
- 【面试题21】包含min函数的栈
- 剑指offer代码解析——面试题21包含min函数的栈
- 剑指Offer---面试题21:包含min函数的栈
- Java - 剑指offer_面试题21_包含min函数的栈
- 面试题21:包含min函数的栈,面试题22:判断某一序列是否是出栈序列
- 剑指Offer面试题21(Java版):包含min函数的栈
- 面试题21:栈:包含min函数的栈
- 面试题21:包含min函数的栈
- 剑指offer 面试题21:包含min函数的栈
- 剑指offer之面试题21:包含min函数的栈
- 剑指Offer面试题20顺时针打印矩阵,面试题21包含min函数的栈
- 面试题21 包含min函数的栈
- 剑指offer-面试题21-包含min函数的栈
- 面试题21:包含min函数的栈
- 【剑指offer】4.3举例让抽象问题具体化——面试题21:包含min函数的栈
- [剑指offer][面试题21]包含min函数的栈
- 【剑指Offer】面试题21:包含min函数的栈
- 剑指offer-面试题21.包含min函数的栈
- 剑指offer面试题[21]包含min函数的栈
- 剑指offer 面试题21 包含min函数的栈 Java实现