kyoo0000

simple_generic_queue.c

Sep 1st, 2021 (edited)
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.01 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct node {
  6.    size_t len;
  7.    void *value;
  8.    struct node *next;
  9. } Node ;
  10.  
  11. Node* init_node(void* value, size_t len) {
  12.    Node* node = (Node*)  calloc(1, sizeof(Node));
  13.    node->len = len, node->value = value, node->next = NULL;
  14.    return node;
  15. }
  16.  
  17. void enqueue(Node *node, void *value) {
  18.    if(value == NULL) return;
  19.    printf("--\n");
  20.    node->len++;
  21.    if(node->next == NULL)
  22.       node->next = init_node(value, 1), printf("aaa\n");
  23.    else
  24.       enqueue(node->next, value);
  25. }
  26.  
  27. void* dequeue(Node **head, size_t n) {
  28.    void *aux = calloc(1, n);
  29.    memcpy(aux, (*head)->value, n);
  30.    
  31.    if((*head)->next == NULL)
  32.       free(head);
  33.    else {
  34.       Node* node_aux = (*head);
  35.       *head = node_aux->next;
  36.       free(node_aux);
  37.    }
  38.      
  39.    return aux;
  40. }
  41.  
  42. void show_queue(Node* head, void (*show_val)(void*)) {
  43.    if(head->next == NULL) {
  44.       show_val(head->value);
  45.       return;
  46.    } else {
  47.       show_val(head->value);
  48.       show_queue(head->next, show_val);
  49.    }
  50. }
  51.  
  52. size_t queue_len(Node* head) { return head->len ;}
  53.  
  54. void show_int(void *n) {
  55.    if(n == NULL)
  56.       printf("Null Pointer\n");
  57.    else {
  58.       int *k = (int*) n;
  59.       printf("%d->", *k);
  60.    }
  61. }
  62.  
  63. int main(void) {
  64.    int n = 5;
  65.    int *arr = (int*) calloc(n, sizeof(int));
  66.    for(int i = 0; i < n; i++)
  67.       *(arr + i) = i + 1, printf("%d ", *(arr + i));
  68.    printf("\n");
  69.    Node* head = init_node(&arr[0], 1);
  70.  
  71.    for(int i = 1; i < n; i++)
  72.       enqueue(head, &arr[i]);
  73.    show_queue(head, &show_int);
  74.  
  75.    int *p = (int*) dequeue(&head, sizeof(int));
  76.    printf("\ndequeue: %d\n", *p);
  77.    show_queue(head, &show_int);
  78.  
  79.    p = (int*) dequeue(&head, sizeof(int));
  80.    printf("\ndequeue: %d\n", *p);
  81.    show_queue(head, &show_int);
  82.  
  83.    p = (int*) dequeue(&head, sizeof(int));
  84.    printf("\ndequeue: %d\n", *p);
  85.    show_queue(head, &show_int);
  86.  
  87.  
  88.    printf("\nTamanho da fila: %zu", queue_len(head));
  89.    return EXIT_SUCCESS;
  90. }
  91.  
  92.  
  93.  
Add Comment
Please, Sign In to add comment