-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxStack.java
More file actions
62 lines (53 loc) · 1.31 KB
/
Copy pathMaxStack.java
File metadata and controls
62 lines (53 loc) · 1.31 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
package Self_Learning.Stack;
import java.util.Scanner;
import java.util.Stack;
class StackMax {
Stack<Integer> stack;
Stack<Integer> maxStack;
StackMax() {
stack = new Stack<>();
maxStack = new Stack<>();
}
void push(int data) {
stack.push(data);
if (maxStack.isEmpty() || data >= maxStack.peek()) {
maxStack.push(data);
}
}
void pop() {
if (stack.isEmpty()) {
return;
}
int remove = stack.pop();
if (!maxStack.isEmpty() && remove == maxStack.peek()) {
maxStack.pop();
}
}
int top() {
if (stack.isEmpty()) {
return -1;
}
return stack.peek();
}
int getMax() {
if (maxStack.isEmpty()) {
return -1;
}
return maxStack.peek();
}
}
public class MaxStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StackMax s = new StackMax();
s.push(sc.nextInt());
s.push(sc.nextInt());
s.push(sc.nextInt());
int max = s.getMax();
System.out.println("Max Value:" + max);
s.pop();
System.out.println("Max value:" + s.getMax());
System.out.println("Top Element:" + s.top());
sc.close();
}
}