1. Title
Min Stack
2. Http address
https://leetcode.com/problems/min-stack/
3. The 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.
4 My code(AC)
-
1 public class MinStack { 2 3 // Accepted 4 public LinkedList<Integer> stack = new LinkedList<Integer>(); 5 public LinkedList<Integer> min_stack = new LinkedList<Integer>(); 6 7 public void push(int x) { 8 9 stack.offerFirst(x); 10 11 if ( min_stack.isEmpty() || x < min_stack.peekFirst()) { 12 min_stack.offerFirst(x); 13 }else{ 14 min_stack.offerFirst(min_stack.peekFirst()); 15 } 16 } 17 18 public void pop() { 19 stack.pollFirst(); 20 min_stack.pollFirst(); 21 } 22 23 public int top() { 24 return stack.peekFirst(); 25 } 26 27 public int getMin() { 28 return min_stack.peekFirst(); 29 } 30 }