标签:
Implement a stack with min() function, which will return the smallest number in the stack.
It should support push, pop and min operation all in O(1) cost.
min operation will never be called if there is no number in the stack.
push(1)
pop() // return 1
push(2)
push(3)
min() // return 2
push(1)
min() // return 1
public class MinStack { class node{ int val; int min; node next; public node(int val){ this.val = val; this.min = Integer.MAX_VALUE; this.next = null; } } private node top; public MinStack() { // do initialize if necessary } public void push(int number) { // write your code here if(this.top == null){ this.top = new node(number); this.top.min = number; } else{ node temp = new node(number); temp.min = Math.min(number, this.top.min); temp.next = this.top; this.top = temp; } return; } public int pop() { // write your code here int result = this.top.val; this.top = top.next; return result; } public int min() { // write your code here return this.top.min; } }
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5339832.html