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

leetcode------Min Stack

时间:2015-01-16 16:26:28      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

标题: 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 }

 

leetcode------Min Stack

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4228680.html

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