Advertisement
193030

Improved search in Linked List

Aug 31st, 2020
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. // Kogato tursim daden element(key), toi stava pyrvi vuv spisyka, taka sledvashtiq pyt vremeto za dostyp e constanta.
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.     struct Node {
  5.     int data;
  6.     struct Node* next;
  7. }* first = NULL;
  8. void create(int A[], int n)
  9. {
  10.     int i;
  11.     struct Node *t, *last;
  12.     first = (struct Node*)malloc(sizeof(struct Node));
  13.     first->data = A[0];
  14.     first->next = NULL;
  15.     last = first;
  16.     for (i = 1; i < n; i++) {
  17.         t = (struct Node*)malloc(sizeof(struct Node));
  18.         t->data = A[i];
  19.         t->next = NULL;
  20.         last->next = t;
  21.         last = t;
  22.     }
  23. }
  24.  
  25. void Display(struct Node* p)
  26. {
  27.     while (p != NULL) {
  28.         printf("%d ", p->data);
  29.         p = p->next;
  30.     }
  31. }
  32.  
  33.  
  34. struct Node* LSearch(struct Node* p, int key)
  35. {
  36.     struct Node* q = NULL;
  37.     while(p!=NULL)
  38.     {
  39.         if(p->data == key)
  40.         {
  41.             q->next = p->next;
  42.             p->next = first;
  43.             first = p;
  44.             return p;
  45.         }
  46.         else
  47.         {
  48.             q = p;
  49.             p = p->next;
  50.         }
  51.  
  52.     }
  53.     return NULL;
  54. }
  55.  
  56.  
  57.  
  58.  
  59. struct Node* RSearch(struct Node* p, int key)
  60. {
  61.     if (p == NULL)
  62.         return NULL;
  63.     if (key == p->data)
  64.         return p;
  65.     return RSearch(p->next, key);
  66. }
  67. int main()
  68. {
  69.     struct Node* temp;
  70.     int A[] = { 3, 5, 7, 10, 25, 8, 32, 2 };
  71.     create(A, 8);
  72.     Display(first);
  73.     printf("\n ");
  74.     temp = LSearch(first, 8);
  75.     printf("% d", temp->data);
  76.     printf("\n ");
  77.     Display(first);
  78.     return 0;
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement