n0va_sa

Dynamic Stack [Table Doubling]

Jul 11th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. // Table Doubling Program with Stack implementation //
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. typedef struct{
  6.     int *arr;
  7.     int top;
  8.     int size;
  9. }stack;
  10.  
  11. void push(stack* sp,int num){
  12.     if(sp->top == sp->size-1){
  13.         int *temp;
  14.         //double the size//
  15.         temp = (int*)malloc(sizeof(int)*sp->size*2);
  16.         if(temp == NULL){
  17.             cout << "failed to allocate";
  18.             return;
  19.         }
  20.         for(int i=0; i <= sp->top ;i++){
  21.             temp[i] = sp->arr[i];
  22.         }
  23.         free(sp->arr);
  24.         sp->arr = temp;
  25.         sp->size *=2;
  26.     }
  27.     sp->top++;
  28.     sp->arr[sp->top] = num;
  29.     return;
  30. }
  31. int pop(stack* sp){
  32.     if(sp->top == -1){
  33.         cout << "Stack Empty\n";
  34.         return -99;
  35.     }
  36.     int num = sp->arr[sp->top];
  37.     sp->top--;
  38.     return num;
  39. }
  40. void freemem(stack* sp){
  41.     if(sp->arr != NULL){
  42.         free(sp->arr);
  43.         sp->top = -1;
  44.         sp-> size = 0;
  45.     }
  46.  
  47. }
  48. void print(stack* sp){
  49.     cout << "Size of Stack: " << sp->size << "\n\n";
  50.     if(sp->top == -1){
  51.         cout << "stack empty\n\n";
  52.         return;
  53.     }
  54.     for (int i=0;i<= sp->top ;i++){
  55.         cout << sp->arr[i] << "\t";
  56.     }
  57.     cout << "\n\n";
  58. }
  59. void __init__(stack* sp,int size){
  60.     sp->top = -1;
  61.     sp->arr = (int*)malloc(sizeof(int)*size);
  62.     if(sp->arr == NULL){
  63.     cout << "cant make allocations\n\n";
  64.     return;
  65.     }
  66.     sp->size = size;
  67.     return;
  68. }
  69. int main(){
  70.     stack s1;
  71.     __init__(&s1,5);
  72.     int choice,num;
  73.     while(1){
  74.         cout << "1: push 2: pop 3: print 4: exit" <<endl;
  75.         cin >> choice;
  76.         switch(choice){
  77.             case 1:
  78.                 cout << "num: ";
  79.                 cin >> num;
  80.                 push(&s1,num);
  81.                 break;
  82.             case 2:
  83.                 num = pop(&s1);
  84.                 cout << num <<endl;
  85.                 break;
  86.             case 3:
  87.                 print(&s1);
  88.                 break;
  89.             case 4:
  90.                 freemem(&s1);
  91.                 exit(0);
  92.             default:
  93.                 cout << "Invalid choice\n\n";
  94.         }
  95.     }
  96.     return 0;
  97. }
Add Comment
Please, Sign In to add comment