C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Maximum and Minimum Element in Linked List

C Program: Maximum and Minimum 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 find maximum and minimum elements

void findMaxMin(struct Node *head, int *max, int *min) {

    struct Node *temp = head;

 

    if (head == NULL) {

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

        *max = *min = 0;

        return;

    }

 

    *max = *min = head->data;

 

    while (temp != NULL) {

        if (temp->data > *max)

            *max = temp->data;

        if (temp->data < *min)

            *min = temp->data;

        temp = temp->next;

    }

}

 

int main() {

    struct Node *head = NULL;

    int n, max, min;

 

    printf("Enter number of nodes: ");

    scanf("%d", &n);

 

    head = createList(n);

    displayList(head);

 

    findMaxMin(head, &max, &min);

 

    printf("\nMaximum element = %d", max);

    printf("\nMinimum element = %d\n", min);

 

    return 0;

}

Output

 
OUTPUT :

Enter number of nodes: 5
Enter data for node 1: 25
Enter data for node 2: 10
Enter data for node 3: 35
Enter data for node 4: 5
Enter data for node 5: 50

Linked List: 25 -> 10 -> 35 -> 5 -> 50 -> NULL

Maximum element = 50
Minimum element = 5

Explanation

Step

Description

1

Create the linked list dynamically using malloc().

2

Initialize both max and min with the first node’s value.

3

Traverse the list and compare each node’s data.

4

Update max and min accordingly.

5

Display the maximum and minimum values at the end.