leetcode------Min Stack

标题: Min Stack
通过率: 15.2%
难度: 简单

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.

本题如果直接用java内置的stack,那么迎刃而解,出这个题的目的就是不让用把。我直接用了模拟栈,头插入链表去解决这个问题,题目相对比较简单,实现的时候做好为空判断和最小值的问题,看代码就能看出来最小值的问题。代码如下:

 1 class MinStack {
 2     Node top = null;
 3 
 4     public void push(int x) {
 5         if (top == null) {
 6             top = new Node(x);
 7             top.min = x;
 8         } else {
 9             Node temp = new Node(x);
10             temp.next = top;
11             top = temp;
12             top.min = Math.min(top.next.min, x);
13         }
14     }
15 
16     public void pop() {
17         top = top.next;
18  
19     }
20 
21     public int top() {
22         return top == null ? 0 : top.val;
23     }
24 
25     public int getMin() {
26         return top == null ? 0 : top.min;
27     }
28 }
29 
30 class Node {
31     int val;
32     int min;
33     Node next;
34 
35     public Node(int val) {
36         this.val = val;
37     }
38 }

 

posted @ 2015-01-16 14:39  pku_smile  阅读(164)  评论(0编辑  收藏  举报