C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Search element in linked list

C Program: Search element in linked list

C

#include <stdio.h>

#include <stdlib.h>

 

// Structure for a node

struct Node {

    int data;

    struct Node *next;

};

 

// Function to create linked list

struct Node* createList(int n) {

    struct Node *head = NULL, *temp, *newNode;

    int data, i;

 

    for (i = 1; i <= n; i++) {

        newNode = (struct Node*)malloc(sizeof(struct Node));

        if (newNode == NULL) {

            printf("Memory allocation failed!\n");

            exit(0);

        }

 

        printf("Enter data for node %d: ", i);

        scanf("%d", &data);

        newNode->data = data;

        newNode->next = NULL;

 

        if (head == NULL)

            head = newNode;

        else

            temp->next = newNode;

 

        temp = newNode;

    }

    return head;

}

 

// Function to display linked list

void displayList(struct Node *head) {

    struct Node *temp = head;

    if (head == NULL) {

        printf("\nList is empty.\n");

        return;

    }

    printf("\nLinked List: ");

    while (temp != NULL) {

        printf("%d -> ", temp->data);

        temp = temp->next;

    }

    printf("NULL\n");

}

 

// Function to search for an element

void searchElement(struct Node *head, int key) {

    struct Node *temp = head;

    int position = 1, found = 0;

 

    if (head == NULL) {

        printf("\nList is empty.\n");

        return;

    }

 

    while (temp != NULL) {

        if (temp->data == key) {

            printf("\nElement %d found at position %d.\n", key, position);

            found = 1;

            break;

        }

        temp = temp->next;

        position++;

    }

 

    if (!found)

        printf("\nElement %d not found in the list.\n", key);

}

 

int main() {

    struct Node *head = NULL;

    int n, key;

 

    printf("Enter number of nodes: ");

    scanf("%d", &n);

 

    head = createList(n);

 

    displayList(head);

 

    printf("\nEnter element to search: ");

    scanf("%d", &key);

 

    searchElement(head, key);

 

    return 0;

}

Output

 
OUTPUT 1 :

Enter number of nodes: 5
Enter data for node 1: 10
Enter data for node 2: 20
Enter data for node 3: 30
Enter data for node 4: 40
Enter data for node 5: 50

Linked List: 10 -> 20 -> 30 -> 40 -> 50 -> NULL

Enter element to search: 30

Element 30 found at position 3.

Explanation

Step

Description

1

Create a linked list dynamically using malloc().

2

Traverse the list node by node.

3

Compare each node’s data with the search key.

4

If found, print the position; otherwise, display “not found.”

5

Keeps track of position using a counter variable.