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