kebria

Insertion in between the nods. Circular singly linked list

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