Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.88 KB | None | 0 0
  1. #define RESZ_AMT 0x100
  2.  
  3. typedef struct {
  4.     void **item;
  5.     size_t sz, rsz;
  6. } stack_t;
  7.  
  8. stack_t *stack_init()
  9. {
  10.     stack_t this = malloc(sizeof(stack_t));
  11.     this->item = malloc(this->rsz = RESZ_AMT);
  12.     this->sz = 0;
  13.     return this;
  14. }
  15.  
  16. void stack_push(stack_t *this, void *item)
  17. {
  18.     if (this->sz == this->rsz) {
  19.         this->item = realloc(this->item, (this->rsz += RESZ_AMT)
  20.                                          * sizeof(void *));
  21.     }
  22.     this->item[this->sz++] = item;
  23. }
  24.  
  25. void *stack_pop(stack_t *this)
  26. {
  27.     if (this->sz == 0) return NULL;
  28.  
  29.     if (--this->sz && this->sz = this->rsz - RESZ_AMT) {
  30.         this->item = realloc(this->item, (this->rsz -= RESZ_AMT)
  31.                                          * sizeof(void *));
  32.     }
  33.     return this->item[this->sz];
  34. }
  35.  
  36. void stack_free(stack_t *this)
  37. {
  38.     free(this->item);
  39.     free(this);
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement