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

Min Stack

时间:2015-11-16 22:47:05      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

1. Title

Min Stack

2. Http address

https://leetcode.com/problems/min-stack/

3. The question

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.

4 My code(AC)

  •  
     1 public class MinStack {
     2 
     3     // Accepted 
     4     public LinkedList<Integer> stack = new LinkedList<Integer>();
     5     public LinkedList<Integer> min_stack = new LinkedList<Integer>();
     6     
     7       public void push(int x) {
     8           
     9               stack.offerFirst(x);
    10               
    11               if ( min_stack.isEmpty() || x < min_stack.peekFirst()) {
    12                   min_stack.offerFirst(x);
    13               }else{
    14                   min_stack.offerFirst(min_stack.peekFirst());
    15               }
    16       }
    17 
    18      public void pop() {
    19             stack.pollFirst();
    20             min_stack.pollFirst();
    21      }
    22 
    23         public int top() {
    24             return stack.peekFirst();
    25         }
    26 
    27         public int getMin() {
    28                 return min_stack.peekFirst();
    29         }
    30 }

     

     

 

 
 

Min Stack

标签:

原文地址:http://www.cnblogs.com/ordili/p/4970062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!