Advertisement
kebria

Creating a circular singly linked list

Jun 18th, 2021
893
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. /* Creating a 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* createList(struct node* tail)
  31. {
  32.     int i, n, data;
  33.     printf("Enter the number of nodes of the linked list: ");
  34.     scanf("%d", &n);
  35.  
  36.     if (n == 0)
  37.         return tail;
  38.     printf("Enter the element 1: ");
  39.     scanf("%d", &data);
  40.     tail = addToEmpty(data);
  41.  
  42.     for (i = 1; i < n; i++)
  43.     {
  44.         printf("Enter the element %d: ", i + 1);
  45.         scanf("%d", &data);
  46.         tail = addAtEnd(tail, data);
  47.     }
  48.     return tail;
  49. }
  50.  
  51. void print(struct node* tail)
  52. {
  53.     if (tail == NULL)
  54.         printf("No node in the list.");
  55.     else
  56.     {
  57.         struct node* p = tail->next;
  58.         do {
  59.             printf("%d ", p->data);
  60.             p = p->next;
  61.         } while (p != tail->next);
  62.     }
  63.     printf("\n");
  64. }
  65.  
  66. int main()
  67. {
  68.     struct node *tail;
  69.     tail = createList(tail);
  70.     print(tail);
  71.     return 0;
  72. }
  73.  
  74.  
  75. /*
  76. Output:
  77. Enter the number of nodes of the linked list : 4
  78. Enter the element 1 : 12
  79. Enter the element 2 : 23
  80. Enter the element 3 : 34
  81. Enter the element 4 : 45
  82. 12 23 34 45
  83. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement