From a40f4d6b27460543530eb502a1398bc7a0bbe44f Mon Sep 17 00:00:00 2001 From: abd171256 <44517978+abd171256@users.noreply.github.com> Date: Sat, 27 Oct 2018 11:47:07 +0530 Subject: [PATCH] Create f6 --- f6 | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 f6 diff --git a/f6 b/f6 new file mode 100644 index 00000000..4d779c6c --- /dev/null +++ b/f6 @@ -0,0 +1,56 @@ + +// A Stack based C++ program to find next +// greater element for all array elements. +#include +using namespace std; + +/* prints element and NGE pair for all +elements of arr[] of size n */ +void printNGE(int arr[], int n) { +stack < int > s; + +/* push the first element to stack */ +s.push(arr[0]); + +// iterate for rest of the elements +for (int i = 1; i < n; i++) { + + if (s.empty()) { + s.push(arr[i]); + continue; + } + + /* if stack is not empty, then + pop an element from stack. + 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 (s.empty() == false && s.top() < arr[i]) + { + cout << s.top() << " --> " << arr[i] << endl; + s.pop(); + } + + /* push next to stack so that we can find + next greater for it */ + s.push(arr[i]); +} + +/* After iterating over the loop, the remaining +elements in stack do not have the next greater +element, so print -1 for them */ +while (s.empty() == false) { + cout << s.top() << " --> " << -1 << endl; + s.pop(); +} +} + +/* Driver program to test above functions */ +int main() { +int arr[] = {11, 13, 21, 3}; +int n = sizeof(arr) / sizeof(arr[0]); +printNGE(arr, n); +return 0; +}