Advertisement
tdudzik

Untitled

Jan 3rd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.47 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3. #include <stdlib.h>
  4.  
  5. /**
  6.  * Stack
  7.  */
  8. typedef struct Stack {
  9.     int maxSize;
  10.     void **values;
  11.     int top;
  12. } Stack;
  13.  
  14. Stack *stack_create(int maxSize) {
  15.     Stack *stack = malloc(sizeof(Stack));
  16.    
  17.     stack->maxSize = maxSize;
  18.    
  19.     void **values = malloc(sizeof(void*) * maxSize);
  20.     stack->values = values;
  21.    
  22.     stack->top = 0;
  23.    
  24.     return stack;
  25. }
  26.  
  27. bool stack_is_empty(Stack *stack) {
  28.     return stack->top == 0;
  29. }
  30.  
  31. bool stack_is_full(Stack *stack) {
  32.     return stack->top == stack->maxSize;
  33. }
  34.  
  35. void *stack_push(Stack *stack, void *value) {
  36.     if (stack_is_full(stack)) {
  37.         return NULL;
  38.     }
  39.    
  40.     stack->values[stack->top++] = value;
  41.     return value;
  42. }
  43.  
  44. void *stack_pop(Stack *stack) {
  45.     if (stack_is_empty(stack)) {
  46.         return NULL;
  47.     }
  48.    
  49.     return stack->values[--stack->top];
  50. }
  51.  
  52. int main(int argc, char** argv) {
  53.     Stack *stack = stack_create(2);
  54.    
  55.     int *x1 = malloc(sizeof(int));
  56.     *x1 = 10;
  57.     stack_push(stack, x1);
  58.    
  59.     int *x2 = malloc(sizeof(int));
  60.     *x2 = 20;
  61.     stack_push(stack, x2);
  62.    
  63.     int *x3 = malloc(sizeof(int));
  64.     *x3 = 30;
  65.    
  66.     bool itWorks = stack_push(stack, x3) == NULL
  67.             && *(int*) stack_pop(stack) == 20
  68.             && *(int*) stack_pop(stack) == 10
  69.             &&  stack_pop(stack) == NULL;
  70.     printf("%s", itWorks ? "IT WORKS! :)" : "IT DOESN'T WORK :(");
  71.    
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement