kebria

Searching an elements. Circular singly linked lis

Jun 20th, 2021
669
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Searching an elements. Cercular singly linked list */
  2. #include <stdio.h>
  3. #include <stdlib.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.  
  31. int searchElement(struct node* tail, int element)
  32. {
  33.     struct node *temp;
  34.     int index = 0;
  35.  
  36.     if (tail == NULL)
  37.         return -2;
  38.  
  39.     temp = tail->next;
  40.     do {
  41.         if (temp->data == element)
  42.             return index;
  43.         temp = temp->next;
  44.         index++;
  45.     } while (temp != tail->next);
  46.     return -1;
  47. }
  48.  
  49. void print(struct node* tail)
  50. {
  51.     if (tail == NULL)
  52.         printf("No node in the list.");
  53.     else
  54.     {
  55.         struct node* p = tail->next;
  56.         do {
  57.             printf("%d ", p->data);
  58.             p = p->next;
  59.         } while (p != tail->next);
  60.     }
  61.     printf("\n");
  62. }
  63.  
  64.  
  65. int main()
  66. {
  67.     struct node *tail = NULL;
  68.     int element;
  69.     tail = addToEmpty(34);
  70.     tail = addAtEnd(tail, 45);
  71.     tail = addAtEnd(tail, 66);
  72.     tail = addAtEnd(tail, 6);
  73.  
  74.     printf("The elements are: ");
  75.     print(tail);
  76.     printf("\nEnter the element u want to search: ");
  77.     scanf("%d", &element);
  78.  
  79.     int index = searchElement(tail, element);
  80.     if (index == -1)
  81.         printf("Element not found\n");
  82.     else if (index == -2)
  83.         printf("Linked list is empty\n");
  84.     else
  85.         printf("Element %d is at index %d\n", element, index);
  86.     return 0;
  87. }
  88.  
  89.  
  90. /*
  91. Output:
  92. The elements are : 34 45 66 6
  93.  
  94. Enter the element u want to search : 66
  95. Element 66 is at index 2
  96. */
RAW Paste Data