码迷,mamicode.com
首页 > 其他好文 > 详细

Min Stack

时间:2015-01-16 18:22:29      阅读:136      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!