首页 > 其他 > 详细

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

时间:2015-09-03 11:32:39      阅读:210      评论:0      收藏:0      [点我收藏+]

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的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 }

 

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

原文:http://www.cnblogs.com/huntertoung/p/4779957.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!