【剑指offer】13,包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
分析:使用两个栈,一个正常存取元素,一个栈用来存储最小的元素,代码如下:
 1 import java.util.Stack;
 2  
 3 public class Solution {
 4  
 5     Stack<Integer> s1 = new Stack<Integer>() ;
 6     Stack<Integer> s2 = new Stack<Integer>() ;
 7    public void push(int node) {
 8         s1.push(node) ;
 9         if(s2.size()==0||node<s2.peek()){
10             s2.push( node) ;
11         }
12         else
13             s2.push( s2.peek());
14     }
15      public int top() {
16             return s1.peek() ;
17         }
18     public void pop() {
19         if(s1.size()>0&&s2.size()>0){
20         s1.pop() ;
21         s2.pop() ;
22         }
23     }
24      
25     public int min() {
26       if(s1.size()>0&&s2.size()>0){
27           return s2.peek() ;
28       }
29       return Integer.MAX_VALUE ;
30     }
31 }

 

posted on 2015-09-03 10:21  小猿之路  阅读(99)  评论(0)    收藏  举报

导航