stack.c 602 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include "stack.h"
  2. struct stack *stack_new()
  3. {
  4. const size_t siz = 1024;
  5. struct stack *s = malloc(sizeof(struct stack *));
  6. s->s = malloc(siz);
  7. s->sp = -1;
  8. s->siz = siz;
  9. return s;
  10. }
  11. int stack_isempty(struct stack *s)
  12. {
  13. return (s->sp == -1);
  14. }
  15. int stack_isfull(struct stack *s)
  16. {
  17. return (s->sp == s->siz);
  18. }
  19. int stack_peek(struct stack *s)
  20. {
  21. if (!stack_isempty(s))
  22. return s->s[s->sp];
  23. return 0;
  24. }
  25. void stack_push(struct stack *s, int item)
  26. {
  27. if (!stack_isfull(s))
  28. s->s[++s->sp] = item;
  29. }
  30. int stack_pop(struct stack *s)
  31. {
  32. if (!stack_isempty(s))
  33. return s->s[s->sp--];
  34. return 0;
  35. }