Thursday, November 25, 2021

Search in Circular linked list

 #include<stdio.h>
#include<stdlib.h>
struct node {
    int data;
    struct node* next;
};
void add(struct node** tail, int val) {
    struct node* temp = malloc(sizeof(struct node));
    if(*tail == NULL) {
        temp->data = val;
        temp->next = temp;
        *tail = temp;
    } else {
        temp->data = val;
        temp->next = (*tail)->next;
        (*tail)->next = temp;
    }
}
void disp(struct node* tail) {
   if(tail == NULL)
     printf("NULL");
   else {
       struct node* p = tail->next;
       do {
           printf("%d", p->data);
           p = p->next;
       }while(p!=tail->next);
       
   }
}
int search(struct node* tail, int val) {
    if(tail == NULL){
        printf("list is empty");
    } else {
        struct node* p = tail->next;
        do {
            if(p->data == val){
                 return 1;
              break;
            }
            else {
                p = p->next;
            }
        } while(p!=tail->next);
        return -1;
    }
}
int main() {
    struct node* tail = NULL;
    add(&tail, 0);
    add(&tail, 1);
    add(&tail, 2);
    add(&tail, 3);
    add(&tail, 4);
    add(&tail, 5);
    disp(tail);
   int x = search(tail, 4);
   if(x==1) {
       printf("\nsearch result found");
   } else {
       printf("\nsearch result not found");
   }

    return 0;
}

No comments:

Post a Comment

Priority queue deleting elements after ascending inputs Gaand Fadd

 using namespace std; #include<iostream> #define N 5 class pq { public:     int* arr;     int front;     int rear;     pq() {         ...