How to delete a node in a linked list at a given Location?

Introducing linked lists and inserting linked lists was covered in a previous post on linked lists of data structures and algorithms.

Let’s create a problem statement to understand the removal process. Specify a “key” to remove the first occurrence of this key in the linked list.

Iterative method:

To remove a node from the linked list, you must perform the following steps:

  1. Find the node before the node you want to remove.
  2. To Change the next of previous node.
  3. Free the memory of the node to delete.

delete a node in a linked list

All nodes in the linked list are dynamically allocated using C’s malloc (), so you have to call free () to free the memory allocated to the node you want to remove.

For example:

delete a node in a linked list

delete a node in a linked list

delete a node in a linked list

Here Code:

#include <bits/stdc++.h>
using namespace std;
class Node{
          int data;
          Node* next;
void push(Node** head_ref, int new_data)
          Node* new_node = new Node();
          new_node->data = new_data;
          new_node->next = (*head_ref);
          (*head_ref) = new_node;
void deleteNode(Node** head_ref, int key)
          Node* temp = *head_ref;
          Node* prev = NULL;
          if (temp != NULL && temp->data == key)
                   *head_ref = temp->next;
                   delete temp;                 
          while (temp != NULL && temp->data != key)
                   prev = temp;
                   temp = temp->next;
          if (temp == NULL)
          prev->next = temp->next;
          delete temp;
void printList(Node* node)
          while (node != NULL)
                   cout << node->data << " ";
                   node = node->next;
int main()
          Node* head = NULL;
          push(&head, 7);
          push(&head, 1);
          push(&head, 3);
          push(&head, 2);
          puts("Created Linked List: ");
          deleteNode(&head, 1);
          puts("\nLinked List after Deletion of 1: ");
          return 0;


In this article, you will learn how to delete a node in a linked list at a specific location.


(Visited 86 times, 1 visits today)

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Ask ChatGPT
Set ChatGPT API key
Find your Secret API key in your ChatGPT User settings and paste it here to connect ChatGPT with your Tutor LMS website.
Would love your thoughts, please comment.x