Advertisement
Miquel_Fuster

Implementación de una pila

Mar 13th, 2022
1,044
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.36 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4.  
  5. typedef struct t_elem{
  6.     int value;
  7.     struct t_elem *next;
  8. } elem;
  9.  
  10. struct {
  11.     elem *top;
  12.     size_t n_elems;
  13. } stack;
  14.  
  15. void stack_initialize() {
  16.     stack.top = NULL;
  17.     stack.n_elems = 0;
  18. }
  19.  
  20. bool stack_push(int value) {
  21.     elem *e = malloc(sizeof(elem));
  22.     if(!e)
  23.         return false;
  24.     e->value = value;
  25.     e->next = stack.top;
  26.     stack.top = e;
  27.     ++stack.n_elems;
  28.     return true;
  29. }
  30.  
  31. bool stack_pop(int *retval) {
  32.     if(!stack.top)
  33.         return false;
  34.     *retval = stack.top->value;
  35.     elem *aux = stack.top;
  36.     stack.top = stack.top->next;
  37.     free(aux);
  38.     --stack.n_elems;
  39.     return true;
  40. }
  41.  
  42. void stack_drop() {
  43.     int dummy;
  44.     while(stack.top)
  45.         stack_pop(&dummy);
  46. }
  47.  
  48. size_t stack_count() {
  49.     return stack.n_elems;
  50. }
  51.  
  52. //////////////////////////////////////////
  53.  
  54. int main() {
  55.     int value;
  56.    
  57.     stack_initialize();
  58.     stack_push(1);
  59.     stack_push(2);
  60.     stack_push(3);
  61.  
  62.     printf("elements in stack: %zu\n", stack_count());
  63.  
  64.     stack_pop(&value);
  65.  
  66.     printf("value popped: %d\n", value);
  67.     printf("elements in stack: %zu\n", stack_count());
  68.  
  69.     stack_drop();
  70.  
  71.     printf("elements in stack: %zu\n", stack_count());
  72.  
  73.     if(!stack_pop(&value)) {
  74.         puts("*** ERROR: The stack is empty!");
  75.     }
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement