dzungchaos

C++ "Int Stack"

Jan 15th, 2020
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. typedef struct intStack {
  5.     int * stackArr;
  6.     int count;
  7.     int top;
  8.     int stackMax;
  9. } intStack;
  10.  
  11. intStack* creatStack(int max){
  12.     intStack* stack;
  13.     stack = new intStack;
  14.     if (stack == NULL)
  15.         return 0;
  16.     stack->stackArr = new int[max];
  17.     stack->count = 0;
  18.     stack->top = -1;
  19.     stack->stackMax = max;
  20.     return stack;  
  21. }
  22.  
  23. void destroyStack(intStack* stack){
  24.     delete [] stack->stackArr;
  25.     delete stack;
  26. }
  27.  
  28. int pushStack(intStack* stack, int val){
  29.     if (stack->count == stack->stackMax)
  30.         return 0;
  31.     (stack->count)++;
  32.     (stack->top)++;
  33.     stack->stackArr[stack->top] = val;
  34.     return 1;
  35. }
  36.  
  37. int popStack(intStack* stack, int* val){
  38.     if (stack->count == 0)
  39.         return 0;
  40.     *val = stack->stackArr[stack->top];
  41.     (stack->count)--;
  42.     (stack->top)--;
  43.     return 1;
  44. }
  45.  
  46. int topStack(intStack* stack, int* val){
  47.     if (stack->count == 0)
  48.         return 0;
  49.     *val = stack->stackArr[stack->top];
  50.     return 1;
  51. }
  52.  
  53. int isEmpty(intStack* stack){
  54.     return !(stack->count);
  55. }
  56.  
  57. int isFull(intStack* stack){
  58.     return (stack->count == stack->stackMax);
  59. }
  60.  
  61. void printStack(intStack* stack){
  62.     for(int i = 0; i < stack->count; i++)
  63.         cout << stack->stackArr[i] << " ";
  64.     cout << endl;
  65. }
  66.  
  67. int main(){
  68.     intStack* stack = creatStack(5);
  69.     int temp;
  70.     pushStack(stack, 10);
  71.     pushStack(stack, 5);
  72.     pushStack(stack, 7);
  73.     pushStack(stack, 8);
  74.     pushStack(stack, -4);
  75.     printStack(stack);
  76.     popStack(stack, &temp);
  77.     printStack(stack);
  78.     popStack(stack, &temp);
  79.     printStack(stack);
  80.     topStack(stack, &temp);
  81.     cout << temp << endl;
  82.     destroyStack(stack);
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment