Delete a Linked List node at a given position in C

C Program to Delete a Node in a Singly Linked List at a specific position

We will be writing a Program in C to delete a node at a given position from a Singly Linked List. We will look at different approaches to Delete a specific node in Linked List in C. Let us check the possible method below –

delete a node

Approach to Delete a specific node in linked list C

  • Accept the Initial Linked List from the user
  • Accept the node position that the user wants to delete
  • Check if it’s a valid position the value should range between [1, size] of the linked list
  • Traverse till the (pos-1)th node
  • Change the next pointer of (pos-1)th node to (pos+1)th node
  • Free the memory for pos’th node.
Delete a specific node in a Linked List in C
Run
// Program for Singly Linked List deletion at a specific position in C
#include <stdio.h>
#include <stdlib.h>

struct Node{
    int data;
    struct Node *next;
};
// current size of Linked List
int size = 0;

void insert(struct Node** head, int data){
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
    
    new_node->data = data;
    new_node->next = *head;
    *head = new_node;
    size++;
}

void deletePosition(int pos, struct Node** head){
    struct Node* temp = *head;
    struct Node* prevNode;
    
    if(pos < 1 || pos > size){
        printf("Invalid\n");
        return;
    }
    
    // delete the 1st node
    if(pos == 1){
        *head = (*head)->next;
        printf("%d deleted\n",temp->data);
        free(temp);
        size--;
        return;
    }
    
    // traverse to the pos'th node
    while (--pos) 
    {
        prevNode = temp; 
        temp = temp->next; 
    }
    // change prevNode node's next node to nth node's next node
    prevNode->next = temp->next;
    // delete this nth node
    printf("%d deleted\n",temp->data);
    free(temp);
    size--; 
}

void display(struct Node* node){
    
    printf("Linked List : ");
    
    // as linked list will end when Node is Null
    while(node!=NULL){
        printf("%d ",node->data);
        node = node->next;
    }
    printf("\n");
}

int main()
{
    struct Node* head = NULL;
    
    insert(&head, 50);
    insert(&head, 40);
    insert(&head, 30);
    insert(&head, 20);
    insert(&head, 10);
    
    display(head); 
   
    // delete the 2nd node
    deletePosition(2, &head);
    
    // delete the 4th node
    deletePosition(4, &head);
    
    display(head); 

    return 0; 
}

Output

Linked List : 10 20 30 40 50 
20 deleted
50 deleted
Linked List : 10 30 40