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.

 https://leetcode.com/problems/min-stack/

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 class MinStack
 5 {
 6     static class Element
 7     {
 8         final int value;
 9         final int min;
10         Element(final int value, final int min)
11         {
12             this.value = value;
13             this.min = min;
14         }
15     }
16     private List<Element> list=new ArrayList();
17     public void push(int x) 
18     {
19         if(list.isEmpty())
20             list.add(new Element(x,x));
21         else
22             list.add(new Element(x,Math.min(x,list.get(list.size()-1).min)));
23     }
24 
25     public void pop() 
26     {
27         list.remove(list.size()-1);//
28     }
29 
30     public int top() 
31     {
32         return list.get(list.size()-1).value;
33     }
34 
35     public int getMin() 
36     {
37         return list.get(list.size()-1).min;
38     }
39 }
 1 public class test
 2 {
 3     public static void main(String[] args)
 4     {
 5         MinStack st=new MinStack();
 6         st.push(5);
 7         st.push(6);
 8 //        st.pop();
 9         int t=st.top();
10         st.push(1);
11         st.push(2);
12         st.push(3);
13         st.push(4);
14         int m=st.getMin();
15     }
16 }
原文地址:https://www.cnblogs.com/qq1029579233/p/4404408.html