Min Stack
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.
这题相当无聊。
1 class MinStack { 2 LinkedList<Integer> stack = new LinkedList<Integer>(); 3 LinkedList<Integer> minimum = new LinkedList<Integer>(); 4 5 public void push(int x) { 6 stack.push(x); 7 if(minimum.size() > 0) minimum.push(minimum.peek() > x ? x : minimum.peek()); 8 else minimum.push(x); 9 } 10 11 public void pop() { 12 stack.pop(); 13 minimum.pop(); 14 } 15 16 public int top() { 17 return stack.peek(); 18 } 19 20 public int getMin() { 21 return minimum.peek(); 22 } 23 }
posted on 2015-01-16 16:06 Step-BY-Step 阅读(118) 评论(0) 编辑 收藏 举报