Delete a Node at a given Position in a Linked List in C++

C++ Program to delete a node from a specific position from a Linked List

Let us look at the C++ Program to delete a node from a given position in a Singly Linked List in C++. We will check various methods to delete a specific node in linked list in C++ via which this can be done.

delete node

Steps Involved to delete a specific node in linked list C++

  • Create a linked list with some nodes in it
  • Ask the user for the node he wants to delete
  • Check if the position mentioned doesn’t violate the linked list size and it is a valid position
  • Traverse to the previous nth node to the one user wants to delete.
  • For this (n-1)th node change its next to (n+1)th node
  • Free the memory for the nth node
Delete a specific node in a Linked List in C++

Delete a linked list node at a given position in C++

// Linked List deletion at a given position in C++
#include<iostream>
using namespace std;

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

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

void deletePosition(int pos, Node** head){
    Node* temp = *head;
    Node* prevNode;
    
    if(pos < 1 || pos > size){
        cout << "Invalid" << endl;
        return;
    }
    
    // delete the 1st node
    if(pos == 1){
        *head = (*head)->next;
        cout << temp->data << " deleted" << endl;
        delete(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 cout << temp->data << " deleted" << endl; delete(temp);
size--; } void display(Node* node){

cout << "Linked List : ";

// as linked list will end when Node is Null
while(node!=NULL){
cout << node->data << " ";
node = node->next;
}
cout << endl;
} int main() { Node* head = NULL; insert(&head, 100); insert(&head, 80); insert(&head, 60); insert(&head, 40); insert(&head, 20); display(head); // delete the 2nd node deletePosition(2, &head); // delete the 4th node deletePosition(4, &head); display(head); return 0; }

Output

Linked List : 20 40 60 80 100 
40 deleted
100 deleted
Linked List : 20 60 80