Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

Delete an element from a singly linked list

$
0
0

Here is the C program to delete an element from a singly linked list.

#include 
#include 

struct node{
    int val;
    struct node *next;
};

struct node * find_node(struct node *head, int val)
{
    struct node *tmp = head;

    while(tmp)
    {
        if (tmp->val == val) return tmp; /*Found*/

        tmp = tmp->next;
    }

    return NULL; /*Not found*/
}

void print_list(struct node *head)
{
    printf("H->");

    while(head)
    {
        printf("%d->", head->val);
        head = head->next;
    }

    printf("|||\n");
}

void insert_front(struct node **head, int value)
{
    struct node * new_node = NULL;

    new_node = (struct node *)malloc(sizeof(struct node));

    if (new_node == NULL)
    {
        printf("Failed to insert element. Out of memory");
    }

    new_node->val = value;
    new_node->next = *head;

    *head = new_node;
}

void delete_elem(struct node **head, int val)
{
    struct node * del = find_node(*head, val);
    struct node * tmp = NULL;

    if (del == NULL) return;

    if (*head == del)
    {
        *head = del->next;
    }
    else
    {
        tmp = *head;

        while(tmp->next != del) tmp = tmp->next;

        tmp->next = del->next;
    }

    free(del);
}

void main()
{
    int count = 0, i, val;
    struct node * head = NULL;

    printf("Enter number of elements: ");
    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("Enter %dth element: ", i);
        scanf("%d", &val);
        insert_front(&head, val);
    }

    printf("Initial List: ");
    print_list(head);

    printf("Enter a value to delete from the list: ");
    scanf("%d", &val);

    delete_elem(&head, val);

    printf("List after deletion: ");
    print_list(head);
}

Output:

Enter number of elements: 5
Enter 0th element: 43
Enter 1th element: 5
Enter 2th element: 10
Enter 3th element: 23
Enter 4th element: 78
Initial List: H->78->23->10->5->43->|||
Enter a value to delete from the list: 10
List after deletion: H->78->23->5->43->|||

The post Delete an element from a singly linked list appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>