Search

PHOTO EMBED

Sun May 14 2023 19:29:03 GMT+0000 (Coordinated Universal Time)

Saved by @prachi

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *prev;
    struct node *next;
};

void insert(struct node **head_ref, int new_data);
void display(struct node *head);
void search(struct node *head, int key);

int main() {
    struct node *head = NULL;
    int n, i, x, key;

    printf("Enter the number of elements in the list: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &x);
        insert(&head, x);
    }

    printf("The elements in the list are: ");
    display(head);

    printf("Enter the element to search: ");
    scanf("%d", &key);

    search(head, key);

    return 0;
}

void insert(struct node **head_ref, int new_data) {
    struct node *new_node = (struct node *)malloc(sizeof(struct node));

    new_node->data = new_data;
    new_node->prev = NULL;
    new_node->next = (*head_ref);

    if ((*head_ref) != NULL) {
        (*head_ref)->prev = new_node;
    }

    (*head_ref) = new_node;
}

void display(struct node *head) {
    struct node *temp = head;

    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }

    printf("\n");
}

void search(struct node *head, int key) {
    struct node *temp = head;
    int pos = 1;

    while (temp != NULL) {
        if (temp->data == key) {
            printf("Element found at position %d with address %p\n", pos, temp);
            return;
        }

        pos++;
        temp = temp->next;
    }

    printf("Element not found in the list\n");
}
content_copyCOPY