-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq3p2.java
More file actions
46 lines (40 loc) · 956 Bytes
/
Copy pathq3p2.java
File metadata and controls
46 lines (40 loc) · 956 Bytes
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
import java.util.*;
public class q3p2{
public static void main(String[] args){
MyStack stk = new MyStack();
stk.myPush(10);
stk.myPush(3);
stk.myPush(1);
stk.myPush(7);
stk.myPush(2);
stk.myPush(4);
System.out.println(stk.min());
}
}
// T: O(n)
// S: O(n)
// A: There is another way, get the elements to a array, and find the leasetest,
// return it.
class MyStack extends Stack<Integer>{
Stack<Integer> s2;
public MyStack(){
s2 = new Stack<Integer>(); // dont forget generics
}
public void myPush(int value){
if(value <= min())
s2.push(value);
push(value);
}
public int myPop(){
int value = pop();
if(value == min())
s2.pop();
return value;
}
public int min(){
if(s2.empty())
return Integer.MAX_VALUE;
else
return s2.peek();
}
}