fork download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. const int MAX_ALLOWED_SIZE = 1000000;
  5.  
  6. template <class T>
  7. class MyStack{
  8. T *a;
  9. int *min, *max;
  10. int top;
  11. int size;
  12.  
  13. public:
  14. MyStack(int s=MAX_ALLOWED_SIZE)
  15. {
  16. //this.size gives this error: request for member `size' in `this', which is of non-class type `MyStack* const'
  17. size = s;
  18. a = new T [size];
  19. min = new int [size];
  20. max = new int [size];
  21. top = -1;
  22. }
  23. void push(T i)
  24. {
  25. if(top == size-1)
  26. {
  27. cout<<"Overflow error"<<endl;
  28. }
  29.  
  30. //if stack has space
  31. else
  32. {
  33. if(top == -1)
  34. {
  35. top++;
  36. min[top] = top;
  37. max[top] = top;
  38. a[top] = i;
  39. }
  40. else if(i <= a[min[top]])
  41. {
  42. top++;
  43. min[top] = top;
  44. a[top] = i;
  45. max[top] = max[top-1];
  46. }
  47.  
  48. else if(i >= a[max[top]])
  49. {
  50. top++;
  51. min[top] = min[top-1];
  52. a[top] = i;
  53. max[top] = top;
  54. }
  55.  
  56. else
  57. {
  58. top++;
  59. min[top] = min[top-1];
  60. a[top] = i;
  61. max[top] = max[top-1];
  62. }
  63. }
  64. }
  65.  
  66. T pop()
  67. {
  68. if(stackEmpty())
  69. {
  70. cout<<"Underflow error"<<endl;
  71. return NULL;
  72. }else return a[top--];
  73. }
  74.  
  75. T maxm()
  76. {
  77. //cout<<"called"<<endl;
  78. if(!stackEmpty())
  79. {
  80. //cout<<max[top]<<" = " <<a[max[top]]<<endl;
  81. return a[max[top]];
  82. }
  83. cout<<"called\n";
  84. return NULL;
  85. }
  86.  
  87. T minm()
  88. {
  89. //cout<<"called"<<endl;
  90. if(!stackEmpty())
  91. {
  92. cout<<"a["<<min[top]<<"] = " <<a[min[top]]<<endl;
  93. return a[min[top]];
  94. }
  95. return NULL;
  96. }
  97.  
  98. T minmm()
  99. {
  100. cout<<"called\t";
  101. if(!stackEmpty())
  102. {
  103. cout<<"a["<<min[top]<<"] = " <<a[min[top]]<<endl;
  104. return a[min[top]];
  105. }
  106. return NULL;
  107. }
  108.  
  109. bool stackEmpty()
  110. {
  111. if(top == -1) return true;
  112. return false;
  113. }
  114.  
  115. void printStack()
  116. {
  117. T s = top+1;
  118. while(s--)
  119. {
  120. printf("a[%d] = %d\n",s,a[s]);
  121. }
  122. }
  123. };
  124.  
  125. int main()
  126. {
  127. MyStack<int> s(5);
  128. int t;
  129.  
  130. while(true)
  131. {
  132. scanf("%d",&t);
  133. s.push(t);
  134. cout<<"min = "<<s.minm()<<endl;
  135. cout<<"min = "<<s.minmm()<<endl;
  136.  
  137. if(t==-1) break;
  138.  
  139. }
  140.  
  141. cout<<"----------"<<endl;
  142. s.printStack();
  143. }
  144.  
Success #stdin #stdout 0s 2864KB
stdin
234
23
-1
stdout
a[0] = 234
min = 234
called	a[0] = 234
min = 234
a[1] = 23
min = 23
called	a[1] = 23
min = 23
a[2] = -1
min = -1
called	a[2] = -1
min = -1
----------
a[2] = -1
a[1] = 23
a[0] = 234