Guest User

Untitled

a guest
Jan 23rd, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "int_stack.h"
  4.  
  5. int main (void)
  6. {
  7.     int curNum; /* index describing the current number */
  8.     tstack stack;
  9.  
  10.     init (&stack); /* stack is initialised */
  11.  
  12.  
  13.     for (curNum=0 ; curNum<VALUES ; curNum++) /* we push some values */
  14.         if (push (&stack, curNum)==0)
  15.             exit (1);
  16.  
  17.  
  18.     for (curNum=0 ; curNum<VALUES ; curNum++) /* values are popped */
  19.     printf ("Number popped: %i\n", pop (&stack));
  20.  
  21.  
  22.     destroy (&stack); /* we destroy stack */
  23.  
  24.     return 0;
  25. }
  26.  
  27. void init(tstack *stack)
  28. {
  29.     stack->top=0;
  30.     stack->numbers=malloc(sizeof(int));
  31. }
  32.  
  33. void destroy (tstack *stack)
  34. {
  35.     free (stack->numbers); /* we free memory */
  36.    
  37. }
  38.  
  39.  
  40. int isempty (tstack *stack)
  41. {
  42.     return (stack->top);
  43. }
  44.  
  45. int push(tstack *stack,int element)
  46. {
  47.     int *temp;
  48.     temp = (int*)realloc(stack->numbers, sizeof(int)*((stack->top)+1));
  49.     if(!(temp))
  50.     {
  51.         free(stack->numbers);
  52.         printf("Error while reallocating memory\n");
  53.         return 0;
  54.     }
  55.     stack->top++;
  56.     stack->numbers=temp;
  57.     (stack->numbers)[stack->top-1]=element;
  58.     return 1;
  59. }
  60.  
  61.  
  62. int pop (tstack *stack)
  63. {
  64.     if (!stack->top)
  65.     {
  66.         printf ("The stack is empty, nothing to pop!\n");
  67.         return 0;
  68.     }
  69.  
  70.     return (stack->numbers [--stack->top]);
  71. }
Add Comment
Please, Sign In to add comment