fork download
  1. /*
  2. Next Greater Element
  3.  
  4.  
  5. */
  6. #include<iostream>
  7. # define maxsize 100
  8. using namespace std;
  9. struct stack{
  10. int top;
  11. int items[maxsize];
  12. };
  13. //function to push an element in satck
  14. void push(struct stack *s,int x){
  15. if(s->top==maxsize-1)
  16. {
  17. cout<<"stack overflow "<<endl;
  18. return;
  19. }
  20. else{
  21. s->top=s->top+1;
  22. //int top=s->top;
  23. s->items[s->top]=x;
  24. }
  25. }
  26. //function to check if satck is empty
  27. bool chkEmpty(struct stack *s){
  28. if(s->top==-1)
  29. return true;
  30. else
  31. return false;
  32. }
  33. //function to pop from stack
  34. int pop(struct stack *s){
  35. if(s->top==-1)
  36. {
  37. cout<<"stack is empty "<<endl;
  38. return -1;
  39. }
  40. else{
  41. int top=s->top;
  42. int temp=s->items[top];
  43. s->top--;
  44. return temp;
  45. }
  46. }
  47. //function to print next greatest element
  48. void printNextGreatest(int A[],int n){
  49. struct stack s;
  50. int i,element,next;
  51. s.top=-1;
  52. //pushing 1st elment in stack
  53. push(&s,A[0]);
  54.  
  55. for(i=1;i<n;i++){
  56. next=A[i];
  57. if(chkEmpty(&s)==false){
  58. //cout<<"Not empty "<<endl;
  59. element=pop(&s);
  60. //cout<<"Elemet is "<<element<<endl;
  61. //cout<<"Next is "<<next<<endl;
  62. while(element<next){
  63. cout<<"Next Greater element of "<<element<<" is "<<next<<endl;
  64. if(chkEmpty(&s))
  65. break;
  66. else {
  67. element=pop(&s);
  68. //cout<<"Element poped is "<<element<<endl;;
  69. }
  70. }
  71. if(element>next)
  72. push(&s,next);
  73. }
  74. push(&s,next);
  75. }
  76. while(chkEmpty(&s)==false){
  77. element=pop(&s);
  78. next=-1;
  79. //cout<<"Next Greater element of "<<element<<" is "<<next<<endl;
  80. }
  81.  
  82.  
  83. }
  84. int main()
  85. {
  86. int n;
  87. cin>>n;
  88. int A[n];
  89. int i;
  90. for(i=0;i<n;i++)
  91. cin>>A[i];
  92. printNextGreatest(A,n);
  93.  
  94. }
  95.  
Success #stdin #stdout 0s 3300KB
stdin
5
1 5 4 7 8
stdout
Next Greater element of 1 is 5
Next Greater element of 4 is 7
Next Greater element of 4 is 7
Next Greater element of 7 is 8