Leetcode - Min Stack
2016-04-30 16:02
393 查看
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.
Note
Your MinStack object will be instantiated and called as such:MinStack obj = new MinStack(); obj.push(x); obj.pop(); int param_3 = obj.top(); int param_4 = obj.getMin();
Java Code
public class MinStack { /** initialize your data structure here. */ class Node { int val; Node next; Node(int x, Node n) { val = x; next = n; } } /** * 实现方式: * 同时维护两个链表,一个用于存储栈内的数据,一个用于储存当前栈内的最小值, * 且两者的push和pop操作保持同步 */ Node head = null; Node minhead = new Node(Integer.MAX_VALUE, null); public MinStack() { } public void push(int x) { head = new Node(x, head); if(x < minhead.val) minhead = new Node(x, minhead); else minhead = new Node(minhead.val, minhead); } public void pop() { head = head.next; minhead = minhead.next; } public int top() { return head.val; } public int getMin() { return minhead.val; } }
相关文章推荐
- JavaScript使用Math.Min返回两个数中较小数的方法
- JQuery中关于jquery.js与jquery.min.js的比较探讨
- Mysql Error Code : 1436 Thread stack overrun
- 基于java中stack与heap的区别,java中的垃圾回收机制的相关介绍
- MySQL中MIN()函数的使用教程
- Python算法之栈(stack)的实现
- Stack数据结构的特点后进先出的应用:大数据运算
- C 堆栈,运行时类型挷定
- jstack和线程dump分析
- c语言stack实现--数据域与指针域分开
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 深入Java虚拟机
- 搭建CloudStack
- 新手,正在学Java Collection,瞎写点东西-一个基于链表的stack及其遍历
- 转贴一份挺好的堆和栈区别的资料
- Mint 7 初体验
- AndroidMenifest.xml中minSdkVersion、targetSdkVersion、targetApiLevel的区别