-
Notifications
You must be signed in to change notification settings - Fork 1
/
stackWithMin.java
83 lines (64 loc) · 1.28 KB
/
stackWithMin.java
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
74
75
76
77
78
79
80
81
82
83
import java.util.Stack;
import java.io.IOException;
public class stackWithMin {
public static void main(String args[]) {
minStack stack = new minStack();
stack.push(4);
stack.push(2);
stack.push(6);
int min = 0;
try {
min = stack.min();
} catch (IOException e) {
}
System.out.println(min);
}
}
class minStack {
Stack stack;
private class IntWithMin {
private int min;
private int data;
public IntWithMin (int x) {
data = x;
min = 0;
}
public void setMin(int x) {
min = x;
}
public int getMin() {
return min;
}
public int getData() {
return data;
}
}
public minStack() {
stack = new Stack();
}
public void push(int x) {
IntWithMin haha = new IntWithMin(x);
if (stack.empty()) {
haha.setMin(x);
} else {
IntWithMin hahatmp = (IntWithMin)stack.peek();
if (hahatmp.getMin() < x)
haha.setMin(hahatmp.getMin());
else
haha.setMin(x);
}
stack.push(haha);
}
public int pop() throws IOException {
if (stack.empty())
throw new IOException();
IntWithMin ret = (IntWithMin)stack.pop();
return ret.getData();
}
public int min() throws IOException {
if (stack.empty())
throw new IOException();
IntWithMin ret = (IntWithMin)stack.peek();
return ret.getMin();
}
}