w3resource

C Exercises: Delete all elements greater than x from a linked list

C Singly Linked List : Exercise-37 with Solution

Write a C program to remove all elements from a singly linked list that are greater than a given value x.

Sample Solution:

C Code:

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

struct Node {
    int data;
    struct Node* next;
};

// Function to create a new node
struct Node* newNode(int data) {
    struct Node* node = (struct Node*) malloc(sizeof(struct Node));
    node->data = data;
    node->next = NULL;
    return node;
}
// Function to delete all elements greater than x from a linked list
void remove_specific(struct Node** head, int x) {
    struct Node* temp = *head;
    struct Node* prev = NULL;

    while (temp != NULL && temp->data > x) {
        *head = temp->next;
        free(temp);
        temp = *head;
    }

    while (temp != NULL) {
        while (temp != NULL && temp->data <= x) {
            prev = temp;
            temp = temp->next;
        }

        if (temp == NULL) {
            return;
        }

        prev->next = temp->next;
        free(temp);
        temp = prev->next;
    }
}

// Function to print a linked list
void displayList(struct Node* head) {
    while (head) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

int main() {
   struct Node* head = newNode(1);
    head->next = newNode(2);
    head->next->next = newNode(3);
    head->next->next->next = newNode(4);
    head->next->next->next->next = newNode(5);
    head->next->next->next->next->next = newNode(6);
    head->next->next->next->next->next ->next = newNode(7);
    printf("Original singly linked list:\n");
	displayList(head);
	printf("\nRemove all elements from the said linked list that are greater than 5:\n");
	remove_specific(&head, 5);
	displayList(head);
    return 0;
}

Sample Output:

Original singly linked list:
1 2 3 4 5 6 7 

Remove all elements from the said linked list that are greater than 5:
1 2 3 4 5 

Flowchart :

Flowchart: Delete all elements greater than x from a linked list.
Flowchart: Delete all elements greater than x from a linked list.

C Programming Code Editor:

Previous: Reverse a singly linked list in blocks of size k.
Next: Pair in a linked list whose sum is equal to a given value.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.