-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetMax.java
More file actions
84 lines (63 loc) · 2.06 KB
/
GetMax.java
File metadata and controls
84 lines (63 loc) · 2.06 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
74
75
76
77
78
79
80
81
82
83
84
// Use the built-in Stack class to implement a new class MaxStack with a method getMax()
// that returns the largest element in the stack. getMax() should not remove the item.
import java.util.EmptyStackException;
import java.util.Stack;
public class GetMax {
Stack<Integer> mainStack = new Stack<Integer>();
Stack<Integer> maxStack = new Stack<Integer>();
// Push to the main stack
// Push to maxstack only if the top of the maxstack is less than the data
public void Push(int data) {
mainStack.push(data);
if(maxStack.isEmpty())
maxStack.push(data);
else if(maxStack.peek() < data)
maxStack.push(data);
}
//Pop only if the maxStack popped data is equal to the top of the maxStack
public void Pop() {
if(!mainStack.isEmpty()) {
if(mainStack.peek() == maxStack.peek()) {
mainStack.pop();
maxStack.pop();
}
else {
mainStack.pop();
}
}
else {
throw new EmptyStackException();
}
}
public static void main(String[] args) {
GetMax getMax = new GetMax();
getMax.Push(10);
getMax.Push(12);
getMax.Push(8);
getMax.Push(14);
getMax.Push(11);
getMax.Push(11);
getMax.Push(9);
getMax.Pop();
System.out.println(getMax.mainStack.peek() + " MAIN");
System.out.println(getMax.maxStack.peek() + " MAX");
getMax.Pop();
System.out.println(getMax.mainStack.peek() + " MAIN");
System.out.println(getMax.maxStack.peek() + " MAX");
getMax.Pop();
System.out.println(getMax.mainStack.peek() + " MAIN");
System.out.println(getMax.maxStack.peek() + " MAX");
getMax.Pop();
System.out.println(getMax.mainStack.peek() + " MAIN");
System.out.println(getMax.maxStack.peek() + " MAX");
getMax.Pop();
System.out.println(getMax.mainStack.peek() + " MAIN");
System.out.println(getMax.maxStack.peek() + " MAX");
getMax.Pop();
System.out.println(getMax.mainStack.peek() + " MAIN");
System.out.println(getMax.maxStack.peek() + " MAX");
getMax.Pop();
System.out.println(getMax.mainStack.peek() + " MAIN");
System.out.println(getMax.maxStack.peek() + " MAX");
}
}