Advertisement
mariopicasso

Untitled

May 25th, 2022
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdbool.h>
  3. #include <stdio.h>
  4. #include <assert.h>
  5. #include "stack.h"
  6.  
  7. static bool invrep(stack s){
  8.     return s != NULL;
  9. }
  10.  
  11. struct _s_stack{
  12.     stack_elem elem;
  13.     stack next;
  14. };
  15.  
  16. stack stack_empty(){
  17.     stack empty_stack = NULL;
  18.     return empty_stack;
  19. }
  20.  
  21. stack stack_push(stack s, stack_elem e){
  22.     stack new_node = malloc(sizeof(stack));
  23.     new_node->elem = e;
  24.     new_node->next = s;
  25.    
  26.     assert(invrep(new_node));
  27.     return new_node;
  28. }
  29.  
  30. stack stack_pop(stack s){
  31.     assert(invrep(s));
  32.    
  33.     stack s_without_head = s->next;
  34.     free(s);
  35.    
  36.     return s_without_head;
  37. }
  38.  
  39. unsigned int stack_size(stack s){
  40.     unsigned int s_size = 0;
  41.     while (s != NULL){
  42.         s = s->next;
  43.         s_size++;
  44.     }
  45.     return s_size;
  46. }
  47.  
  48. stack_elem stack_top(stack s){
  49.     assert(invrep(s));
  50.     return s->elem;
  51. }
  52.  
  53. bool stack_is_empty(stack s){
  54.     return (s == NULL);
  55. }
  56.  
  57.  
  58. stack_elem *stack_to_array(stack s){
  59.     printf("a");
  60.     if (stack_is_empty(s)){
  61.         return NULL;
  62.     }
  63.     printf("b");
  64.    
  65.     assert(invrep(s));
  66.    
  67.     stack aux = s;
  68.     unsigned int len = stack_size(s);
  69.     stack_elem *a = calloc(len, sizeof(stack_elem));
  70.     unsigned int i = len;
  71.    
  72.     for(unsigned int i = len - 1u; i <= 0u ; i--){
  73.         a[i] = aux->elem;
  74.         aux = aux->next;
  75.     }
  76.  
  77.     assert(invrep(s));
  78.     return a;
  79. }
  80.  
  81.  
  82. stack destroy(stack s){
  83.     assert(invrep(s));
  84.     stack d;
  85.     while (s->next != NULL){
  86.         d = s->next;
  87.         free(s);
  88.     }
  89.     free(d);
  90.     return NULL;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement