fork(3) download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Stack
  6. {
  7. private:
  8. /* int *p;
  9.   int top,length;*/
  10.  
  11. public:
  12. int *p;
  13. int top,length;
  14. Stack(int = 0);
  15. ~Stack();
  16.  
  17. void push(int);
  18. int pop();
  19. int func();
  20. void display();
  21. void Swap();
  22. bool isEmpty();
  23. bool isFull();
  24. };
  25.  
  26. Stack::Stack(int size)
  27. {
  28. top=-1;
  29. length=size;
  30. if(size == 0)
  31. p = 0;
  32. else
  33. p=new int[length];
  34. }
  35.  
  36. Stack::~Stack()
  37. {
  38. if(p!=0)
  39. delete [] p;
  40. }
  41.  
  42. void Stack::push(int elem)
  43. {
  44. if(p == 0) //If the stack size is zero, allow user to mention it at runtime
  45. {
  46. cout<<"Stack of zero size"<<endl;
  47. cout<<"Enter a size for stack : ";
  48. cin >> length;
  49. p=new int[length];
  50. }
  51. if(top==(length-1)) //If the top reaches to the maximum stack size
  52. {
  53. cout<<"\nCannot push "<<elem<<", Stack full"<<endl;
  54. return;
  55. }
  56. else
  57. {
  58. top++;
  59. p[top]=elem;
  60. }
  61. }
  62. int Stack::pop()
  63. {
  64. if(p==0 || top==-1)
  65. {
  66. cout<<"Stack empty!";
  67. return -1;
  68. }
  69. int ret=p[top];
  70. top--;
  71. return ret;
  72. }
  73.  
  74. void Stack::display()
  75. {
  76. for(int i = 0; i <= top; i++)
  77. cout<<p[i]<<" ";
  78. cout<<endl;
  79. }
  80.  
  81. bool Stack::isEmpty()
  82. {
  83. if(p==0 || top==-1){return 1;}
  84. else return 0;
  85. }
  86. bool Stack::isFull()
  87. {
  88. if (top==length){return 1;}
  89. else return 0;
  90. }
  91.  
  92. void Swap(Stack &x){
  93. int sz=x.length,mytop,mybottom;
  94. mytop=x.top;
  95. x.pop();
  96. int tmp[sz-1],i=0;
  97. while(!x.isEmpty()){
  98. mybottom=x.top;
  99. tmp[i++]=mybottom;
  100. x.pop();
  101. }
  102. Stack returnIt;
  103. returnIt.push(mybottom);
  104. for(i=0;i<=sz-3;i++){
  105. returnIt.push(tmp[i]);
  106. }
  107. returnIt.push(mytop);
  108. while(!returnIt.isEmpty()){
  109. int tt=returnIt.top;
  110. x.push(tt);
  111. returnIt.pop();
  112. }
  113. }
  114. int main()
  115. {
  116. Stack s1;
  117. s1.push(1);
  118. s1.push(2);
  119. s1.push(3);
  120. s1.push(4);
  121. s1.push(5);
  122. s1.push(6);
  123. s1.push(7);
  124. s1.push(8);
  125. s1.push(9);
  126. s1.display();
  127. Swap(s1);
  128. s1.display();
  129. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
Stack of zero size
Enter a size for stack : 
Cannot push 1, Stack full

Cannot push 2, Stack full

Cannot push 3, Stack full

Cannot push 4, Stack full

Cannot push 5, Stack full

Cannot push 6, Stack full

Cannot push 7, Stack full

Cannot push 8, Stack full

Cannot push 9, Stack full

Stack empty!Stack of zero size
Enter a size for stack : 
Cannot push -1081335660, Stack full

Cannot push -1, Stack full