kebria

Insertion between the nodes. Circular doubly linked lis

Jun 20th, 2021
594
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Insertion between the nodes. 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. struct node *addAfterPos(struct node* tail, int data, int pos)
  54. {
  55.     struct node *newP = addToEmpty(data);
  56.     if (tail == NULL)
  57.         return newP;
  58.     struct node *temp = tail->next;
  59.     while (pos > 1)
  60.     {
  61.         temp = temp->next;
  62.         pos--;
  63.     }
  64.     newP->prev = temp;
  65.     newP->next = temp->next;
  66.     temp->next->prev = newP;
  67.     temp->next = newP;
  68.     if (temp == tail)
  69.         tail = tail->next;
  70.     return tail;
  71. }
  72.  
  73. void print(struct node* tail)
  74. {
  75.     if (tail == NULL)
  76.         printf("No element in the list\n");
  77.     else
  78.     {
  79.         struct node *temp = tail->next;
  80.         do {
  81.             printf("%d ", temp->data);
  82.             temp = temp->next;
  83.         } while (temp != tail->next);
  84.     }
  85.     printf("\n");
  86. }
  87.  
  88. int main()
  89. {
  90.     struct node *tail = NULL;
  91.     tail = addToEmpty(45);
  92.     /* tail = addAtBeg(tail, 34); */
  93.     tail = addAtEnd(tail, 56);
  94.     tail = addAtEnd(tail, 60);
  95.     tail = addAfterPos(tail, 90, 2);
  96.     print(tail);
  97.     return 0;
  98. }
  99.  
  100. //Output: 45 56 90 60
  101.  
  102.  
RAW Paste Data