fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4.  
  5. typedef struct {
  6. int *items;
  7. size_t len;
  8. size_t capacity;
  9. } Stack;
  10.  
  11. Stack stack_new(void)
  12. {
  13. Stack stack = {
  14. .items = NULL,
  15. .len = 0,
  16. .capacity = 0
  17. };
  18.  
  19. return stack;
  20. }
  21.  
  22. void stack_push(Stack *stack, int value)
  23. {
  24. if (stack->len == stack->capacity) {
  25. size_t new_capacity = stack->capacity == 0
  26. ? 4
  27. : stack->capacity * 2;
  28.  
  29. int *new_items = realloc(
  30. stack->items,
  31. new_capacity * sizeof(int)
  32. );
  33.  
  34. if (new_items == NULL) {
  35. exit(EXIT_FAILURE);
  36. }
  37.  
  38. stack->items = new_items;
  39. stack->capacity = new_capacity;
  40. }
  41.  
  42. stack->items[stack->len] = value;
  43. stack->len++;
  44. }
  45.  
  46. bool stack_pop(Stack *stack, int *value)
  47. {
  48. if (stack->len == 0) {
  49. return false;
  50. }
  51.  
  52. stack->len--;
  53. *value = stack->items[stack->len];
  54.  
  55. return true;
  56. }
  57.  
  58. bool stack_peek(const Stack *stack, int *value)
  59. {
  60. if (stack->len == 0) {
  61. return false;
  62. }
  63.  
  64. *value = stack->items[stack->len - 1];
  65.  
  66. return true;
  67. }
  68.  
  69. bool stack_is_empty(const Stack *stack)
  70. {
  71. return stack->len == 0;
  72. }
  73.  
  74. size_t stack_len(const Stack *stack)
  75. {
  76. return stack->len;
  77. }
  78.  
  79. void stack_free(Stack *stack)
  80. {
  81. free(stack->items);
  82.  
  83. stack->items = NULL;
  84. stack->len = 0;
  85. stack->capacity = 0;
  86. }
  87.  
  88. int main(void)
  89. {
  90. Stack stack = stack_new();
  91.  
  92. stack_push(&stack, 10);
  93. stack_push(&stack, 20);
  94. stack_push(&stack, 30);
  95.  
  96. printf("len = %zu\n", stack_len(&stack));
  97.  
  98. int value;
  99.  
  100. if (stack_peek(&stack, &value)) {
  101. printf("peek = %d\n", value);
  102. }
  103.  
  104. if (stack_pop(&stack, &value)) {
  105. printf("pop = %d\n", value);
  106. }
  107.  
  108. if (stack_pop(&stack, &value)) {
  109. printf("pop = %d\n", value);
  110. }
  111.  
  112. printf("len = %zu\n", stack_len(&stack));
  113. printf("empty = %s\n",
  114. stack_is_empty(&stack) ? "true" : "false");
  115.  
  116. stack_free(&stack);
  117.  
  118. return 0;
  119. }
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout
len = 3
peek = 30
pop = 30
pop = 20
len = 1
empty = false