#include <bits/stdc++.h>
using namespace std;
void print(int *a, int n)
{
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}
void replace(int *a, int n)
{
int i = 0;
stack<int> s; // craeting a stack using stl
int e, nextNearestGreater; // create variable nextNearestGreater
s.push(a[0]); // push the first element
for (int i = 1; i < n; i++)
{ // for the rest of the array
// set nextNearestGreater to the current element
nextNearestGreater = a[i];
// if stack is not empty
if (!s.empty())
{
e = s.top();
// pop from stack
s.pop();
// if nextNearestGreater is greater than popped element
while (e < nextNearestGreater)
{
// replacing the current element with nextNearestGreater
// as it's the next greater element
cout << "nearest greater element of " << e << " is " << nextNearestGreater << endl;
if (s.empty())
break;
e = s.top();
// continue popping till nextNearestGreater is greater
s.pop();
}
// if popped element is greater than nextNearestGreater then push to stack
if (e > nextNearestGreater)
s.push(e);
}
s.push(nextNearestGreater);
}
while (!s.empty())
{
e = s.top();
s.pop();
cout << "nearest greater element of " << e << " is " << e << " (no nearest greater number on the right side)" << endl; // since no number is greater in right of e
}
}
int main()
{
int n;
// enter array length
cout << "enter size of data\n";
cin >> n;
int *a = (int *)(malloc(sizeof(int) * n));
// fill the array
cout << "enter data\n";
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
cout << "finding nearest greater numbers for each data\n"
<< endl;
replace(a, n);
// print(a,n);
return 0;
}
Output
enter size of data
5
enter data
1
2
3
4
5
finding nearest greater numbers for each data
nearest greater element of 1 is 2
nearest greater element of 2 is 3
nearest greater element of 3 is 4
nearest greater element of 4 is 5
nearest greater element of 5 is 5 (no nearest greater number on the right side)
0 Comments