首页 > 其他 > 详细

Min Stack

时间:2015-01-16 18:20:09      阅读:261      评论:0      收藏:0      [点我收藏+]

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

这题相当无聊。

 1 class MinStack {
 2     LinkedList<Integer> stack = new LinkedList<Integer>();
 3     LinkedList<Integer> minimum = new LinkedList<Integer>();
 4     
 5     public void push(int x) {
 6         stack.push(x);
 7         if(minimum.size() > 0) minimum.push(minimum.peek() > x ? x : minimum.peek());
 8         else minimum.push(x);
 9     }
10 
11     public void pop() {
12         stack.pop();
13         minimum.pop();
14     }
15 
16     public int top() {
17         return stack.peek();
18     }
19 
20     public int getMin() {
21         return minimum.peek();
22     }
23 }

 

Min Stack

原文:http://www.cnblogs.com/reynold-lei/p/4229025.html

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