Miquel_Fuster

Circular doubly linked list: add item and drop list

Mar 26th, 2022 (edited)
1,033
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.99 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node {
  5.     int data;
  6.     struct node* prev;
  7.     struct node* next;
  8. } node;
  9.  
  10. node* add(node **head, int data) {
  11.     node *new = malloc(sizeof(node));
  12.     if(!new) {
  13.         return NULL;
  14.     }
  15.  
  16.     new->data = data;
  17.  
  18.     if(*head) {
  19.         new->prev = (*head)->prev;
  20.         new->next = *head;
  21.         (*head)->prev->next = new;
  22.         (*head)->prev = new;
  23.     } else {
  24.         new->next = new;
  25.         new->prev = new;
  26.         *head = new;
  27.     }
  28.  
  29.     return new;
  30. }
  31.  
  32. void drop(node **head) {
  33.     node *aux;
  34.     if(!*head) {
  35.         return;
  36.     }
  37.  
  38.     (*head)->prev->next = NULL;
  39.     while(*head) {
  40.         aux = *head;
  41.         *head = (*head)->next;
  42.         free(aux);
  43.     }
  44. }
  45.  
  46. int main() {
  47.     node *list = NULL;
  48.     add(&list, 0);
  49.     add(&list, 1);
  50.     add(&list, 2);
  51.  
  52.     printf("%d ", list->data);
  53.     printf("%d ", list->next->data);
  54.     printf("%d ", list->prev->data);
  55.    
  56.     drop(&list);
  57. }
Add Comment
Please, Sign In to add comment