-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathP9.java
More file actions
84 lines (72 loc) · 2.39 KB
/
P9.java
File metadata and controls
84 lines (72 loc) · 2.39 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
package stack_and_queue;
// Problem Title => Find the next Greater Element
public class P9 {
static class stack {
int top;
int[] items = new int[100];
// Stack functions to be used by printNGE
void push(int x) {
if (top == 99) {
System.out.println("Stack full");
}
else {
items[++top] = x;
}
}
int pop() {
if (top == -1) {
System.out.println("Underflow error");
return -1;
}
else {
int element = items[top];
top--;
return element;
}
}
boolean isEmpty() {
return top == -1;
}
}
/* prints element and NGE pair for all elements of arr[] of size n */
static void printNGE(int[] arr, int n) {
int i;
stack s = new stack();
s.top = -1;
int element, next;
/* push the first element to stack */
s.push(arr[0]);
// iterate for rest of the elements
for (i = 1; i < n; i++) {
next = arr[i];
if (!s.isEmpty()) {
// if stack is not empty, then pop an element from stack
element = s.pop();
/* If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */
while (element < next) {
System.out.println(element + " --> " + next);
if (s.isEmpty())
break;
element = s.pop();
}
/* If element is greater than next, then push the element back */
if (element > next)
s.push(element);
}
/* push next to stack so that we can find next greater for it */
s.push(next);
}
/* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */
while (!s.isEmpty()) {
element = s.pop();
next = -1;
System.out.println(element + " -- " + next);
}
}
// Driver Code
public static void main(String[] args) {
int[] arr = { 11, 13, 21, 3 };
int n = arr.length;
printNGE(arr, n);
}
}