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{
public:
          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;                 
                   return;
          }
          else
          {
          while (temp != NULL && temp->data != key)
          {
                   prev = temp;
                   temp = temp->next;
          }
          if (temp == NULL)
                   return;
          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: ");
          printList(head);
          deleteNode(&head, 1);
          puts("\nLinked List after Deletion of 1: ");
          printList(head); 
          return 0;
}

Conclusion:

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

References:

(Visited 86 times, 1 visits today)

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
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.
0
Would love your thoughts, please comment.x
()
x