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:
- Find the node before the node you want to remove.
- To Change the next of previous node.
- Free the memory of the node to delete.
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:
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.