Question:
Deleting a Node in Single Linked list with c

Summary:

This C++ code defines a function deleteNode to delete a node from a linked list given the position of the node to be deleted. It takes the head of the linked list and the position x as parameters. If the given position is the first node, it updates the head pointer accordingly. Otherwise, it traverses the linked list to find the node at position x, adjusts the pointers of the previous and next nodes, deletes the node, and returns the updated head pointer.


Solution:

/* Link list Node 

struct Node

{

    int data;

    struct Node* next;

    

    Node(int x){

        data = x;

        next = NULL;

    }

};

*/


/*You are required to complete below method*/

Node* deleteNode(Node *head,int x)

{

    if(head==NULL ){

        return head;

    }

    if(x==1){

        Node* temp=head;

        head=head->next;

        delete temp;

        return head;

    }

    int count=1;

    Node* temp=head;

    Node* prev=NULL;

    while(temp!=NULL && count<x){

        prev=temp;

        temp=temp->next;

        count++;

    }

    Node* to=temp;

    prev->next=temp->next;

    delete to;

    return head;

    //Your code here

}


Explanation:

  1. The function deleteNode takes two parameters: head, a pointer to the head of the linked list, and x, the position of the node to be deleted.

  2. It first checks if the linked list is empty (head == NULL) or if the position to delete is the first node (x == 1). If either condition is true, it deletes the first node and updates the head pointer accordingly.

  3. If neither of the above conditions is true, it initializes count to 1 and traverses the linked list using a while loop until it reaches the node at position x or the end of the list.

  4. Inside the loop, it maintains two pointers: temp to traverse the list and prev to keep track of the previous node.

  5. Once the node at position x is found (temp), it updates the pointers of the previous node (prev->next) to skip the node to be deleted and point directly to the next node.

  6. It then deletes the node at position x (temp) and returns the updated head pointer.

  7. The function completes, and the deleted node is removed from the linked list.


Suggested blogs:

>Python Error Solved: load_associated_files do not load a txt file

>Python Error Solved: pg_config executable not found

>Set up Node.js & connect to a MongoDB Database Using Node.js

>Setting up a Cloud Composer environment: Step-by-step guide

>What is microservice architecture, and why is it better than monolithic architecture?

>What is pipe in Angular?

>What makes Python 'flow' with HTML nicely as compared to PHP?

>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?

>Creating custom required rule - Laravel validation

>How to configure transfers for different accounts in stripe with laravel?


Ritu Singh

Ritu Singh

Submit
0 Answers