Advertisement
biznesman

list.c

Dec 5th, 2022
378
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #include "list.h"
  5. #include "errs.h"
  6.  
  7. void free_list(node_t *head)
  8. {
  9.     node_t *tmp = head;
  10.     for (; head; head = tmp)
  11.     {
  12.         tmp = head->next;
  13.         free(head);
  14.         head = NULL;
  15.     }
  16. }
  17.  
  18. int print_list(node_t * head)
  19. {
  20.     int rc = (head == NULL) * ERR_NULL_HEAD;
  21.     if (!rc)
  22.     {
  23.         for (node_t *tmp = head; tmp; tmp = tmp->next)
  24.             printf("%d ", tmp->data);
  25.         printf("\n");
  26.     }
  27.     return rc;
  28. }
  29.  
  30. node_t *create_node(int data)
  31. {
  32.     node_t *temp = malloc(sizeof(node_t));
  33.     if (temp)
  34.     {
  35.         temp->data = data;
  36.         temp->next = NULL;
  37.     }
  38.  
  39.     return temp;
  40. }
  41.  
  42. int pop_front(node_t **head)
  43. {
  44.     int pop_data = 0;
  45.     if (head != NULL && *head != NULL)
  46.     {
  47.         node_t *prev = *head;
  48.         pop_data = (*head)->data;
  49.         *head = (*head)->next;
  50.         free(prev);
  51.     }
  52.  
  53.     return pop_data;
  54. }
  55.  
  56. int pop_back(node_t **head)
  57. {
  58.     int pop_data = 0;
  59.     if (head != NULL && *head != NULL)
  60.     {
  61.         node_t *tmp = *head;
  62.         node_t *prev_tmp = tmp;
  63.         for (; tmp->next; prev_tmp = tmp, tmp = tmp->next);
  64.         pop_data = tmp->data;
  65.         prev_tmp->next = NULL;
  66.         free(tmp);
  67.         if (*head == tmp)
  68.             *head = NULL;
  69.     }  
  70.  
  71.     return pop_data;
  72. }
  73.  
  74. int push_back_value(node_t **head, int data)
  75. {
  76.     int rc = (head == NULL) * ERR_NULL_HEAD;
  77.     if (!rc)
  78.     {
  79.         node_t *new_node = create_node(data);
  80.         if (*head == NULL)
  81.             *head = new_node;
  82.         else
  83.         {
  84.             node_t *tmp = *head;
  85.             for (; tmp->next; tmp = tmp->next);
  86.             tmp->next = new_node;
  87.         }
  88.     }
  89.    
  90.     return rc;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement