forked from christine-1017/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
73 lines (64 loc) · 1.42 KB
/
MinStack.java
File metadata and controls
73 lines (64 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package datastructure;
import java.util.Stack;
/*
* Memory limits (The min stack should not have same number of elements with the stack. Just keep track of the smallest elements)
*
* Duplicate elements. (less or equal than, push into min stack).
*
*/
public class MinStack {
static Stack<Integer> stack;
static Stack<Integer> minStack;
public MinStack_Stack(){
stack = new Stack<Integer>();
minStack = new Stack<Integer>();
}
public void push(int x){
stack.push(x);
if(minStack.isEmpty() || minStack.peek() >= x)
minStack.push(x);
}
public void pop(){
if(minStack.peek().equals(stack.peek()))
minStack.pop();
stack.pop();
}
public int top(){
return stack.peek();
}
public int getMin(){
return minStack.peek();
}
public static void main(String[] args) {
MinStack s = new MinStack();
s.push(10);
s.push(20);
s.push(1);
s.push(1);
s.push(20);
s.push(11);
s.push(12);
s.push(5);
s.push(5);
System.out.println(s.top());
s.pop();
System.out.println(s.getMin());
System.out.println(s.top());
s.pop();
System.out.println(s.getMin());
System.out.println(s.top());
s.pop();
System.out.println(s.getMin());
System.out.println(s.top());
s.pop();
System.out.println(s.getMin());
System.out.println(s.top());
s.pop();
System.out.println(s.top());
s.pop();
System.out.println(s.top());
s.pop();
System.out.println(s.top());
s.pop();
}
}