Deleting a Node from Linked List

Problem statement: Given a number, delete the first occurrence of that number in the linked list.

Iterative Solution
1) Find the previous node of the node that is to be deleted.
2) Assign the next of the previous node.
3) Free(temp).
/*C code to delete an node from the Linked List */
#include <stdio.h>
#include <stdlib.h>
 
typedef struct node
{
    int data;
    struct node *next;
} NODE;
 
NODE *head = NULL;
 
NODE *newNode(int key)
{
    NODE *temp = (NODE *)malloc(sizeof(NODE));
    temp->data = key;
    temp->next = NULL;
    return temp;
}
 
NODE *deleteNode(NODE *head, int key)
{
    NODE *temp = head, *prev;
    if (temp != NULL && temp->data == key)
    {
        printf("%d is deleted from the Linked List!\n", key);
        head = temp->next;
        free(temp);
        return head;
    }
    while (temp != NULL && temp->data != key)
    {
        prev = temp;
        temp = temp->next;
    }
    if (temp == NULL)
    {
        printf("%d is not present in the Linked List!\n", key);
        return head;
    }
    prev->next = temp->next;
    printf("%d is deleted from the Linked List!\n", key);
    free(temp);
    return head;
}
 
void printList()
{
    NODE *temp = head;
    if (temp == NULL)
    {
        printf("List is empty!\n");
        return;
    }
    printf("Linked List is\t");
    while (temp != NULL)
    {
        printf("%d--> ", temp->data);
        temp = temp->next;
    }
    printf("NULL\n");
}
 
int main()
{
    head = newNode(1);
    head->next = newNode(2);
    head->next->next = newNode(3);
    head->next->next->next = newNode(4);
    head->next->next->next->next = NULL;
    printList();
    int key;
    printf("Enter the key to delete\t");
    scanf("%d", &key);
    head = deleteNode(head, key);
    printList();
    return 0;
}
$ gcc delete_node.c
$ ./a.out
Linked List is 1–> 2–> 3–> 4–> NULL
Enter the key to delete 1
1 is deleted from the Linked List!
Linked List is 2–> 3–> 4–> NULL
$ ./a.out
Linked List is 1–> 2–> 3–> 4–> NULL
Enter the key to delete 3
3 is deleted from the Linked List!
Linked List is 1–> 2–> 4–> NULL
$ ./a.out
Linked List is 1–> 2–> 3–> 4–> NULL
Enter the key to delete 7
7 is not present in the Linked List!
Linked List is 1–> 2–> 3–> 4–> NULL
$

also see

C Programming language
Go Programming language
Linked List Array
Stack Queue
Puzzle Reasoning
Aptitude HTML
Previous articleAnalogy Set I
Next articleHTML Tags Set I

LEAVE A REPLY

Please enter your comment!
Please enter your name here