Offer nineteenth prove safety problem: min function comprising a stack of

Stack data structure definition, implement this type can be a min function smallest elements contained in the stack (should the time complexity O (1)).

Due itself to the import java.util.Stack; so it feels can use JDK comes with the stack

Ideas: for two recording stacks, s1 record all, s2 each time the minimum recording

Source as follows:

 1 import java.util.Stack;
 2 
 3 public class Solution {
 4 
 5     Stack<Integer> s1 = new Stack();
 6     Stack<Integer> s2 = new Stack();
 7     
 8     public void push(int node) {
 9         s1.push(node);
10         if(s2.empty())
11             s2.push(node);
12         else{
13             if(node<s2.peek())
14                 s2.push(node);
15         }
16     }
17     
18     public void pop() {
19         if(s1.peek()==s2.peek()){
20             s1.pop();
21             s2.pop();
22         }else{
23             s1.pop();
24         }
25     }
26     
27     public int top() {
28         return s1.peek();
29     }
30     
31     public int min() {
32         return s2.peek();
33     }
34 }

Guess you like

Origin www.cnblogs.com/haq123/p/12181653.html