kebria

Insertion at the end. Circular doubly linked lis

Jun 20th, 2021
837
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Insertion at the end. Circular doubly linked list */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. struct node {
  6.     struct node *prev;
  7.     int data;
  8.     struct node *next;
  9. };
  10.  
  11. struct node* addToEmpty(int data)
  12. {
  13.     struct node* temp = malloc(sizeof(struct node));
  14.     temp->prev = temp;
  15.     temp->data = data;
  16.     temp->next = temp;
  17.     return temp;
  18. }
  19.  
  20. struct node* addAtBeg(struct node* tail, int data)
  21. {
  22.     struct node *temp = tail->next;
  23.     struct node *newP = malloc(sizeof(struct node));
  24.     newP->prev = NULL;
  25.     newP->data = data;
  26.     newP->next = NULL;
  27.  
  28.     newP->prev = tail;
  29.     newP->next = temp;
  30.     temp->prev = newP;
  31.     tail->next = newP;
  32.     return tail;
  33.    
  34. }
  35.  
  36. struct node* addAtEnd(struct node* tail, int data)
  37. {
  38.     struct node *newP = addToEmpty(data);
  39.     if (tail == NULL)
  40.         return newP;
  41.     else
  42.     {
  43.         struct node *temp = tail->next;
  44.         newP->next = temp;
  45.         newP->prev = tail;
  46.         tail->next = newP;
  47.         temp->prev = newP;
  48.         tail = newP;
  49.         return tail;
  50.     }
  51. }
  52.  
  53. void print(struct node* tail)
  54. {
  55.     if (tail == NULL)
  56.         printf("No element in the list\n");
  57.     else
  58.     {
  59.         struct node *temp = tail->next;
  60.         do {
  61.             printf("%d ", temp->data);
  62.             temp = temp->next;
  63.         } while (temp != tail->next);
  64.     }
  65.     printf("\n");
  66. }
  67.  
  68. int main()
  69. {
  70.     struct node *tail = NULL;
  71.     tail = addToEmpty(45);
  72.     tail = addAtBeg(tail, 34);
  73.     tail = addAtEnd(tail, 56);
  74.     print(tail);
  75.     return 0;
  76. }
  77.  
  78. //Output: 34 45 56
RAW Paste Data