delete the node without the head node

You are given a pointer/reference to a node to be deleted in a linked list. The task is to delete the node.  Pointer/reference to head node is not given. 
You may assume that the node to be deleted is not the last node.
Input:
You have to complete a method which takes one argument: pointer/reference to a node to be deleted.  There are multiple test cases. For each test case, this method will be called individually.

Example:Input
2
2
1 2
1
4
10 20 4 3020
20

Output
2
10 4 30
simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires pointer to the head node which contradicts the problem statement.
Fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like following.
    // Find next node using next pointer
    struct Node *temp  = node_ptr->next;

    // Copy data of next node to this node
    node_ptr->data  = temp->data;

    // Unlink next node
    node_ptr->next  = temp->next;

    // Delete next node
    free(temp);

void deleteNode(Node *node)
{
   // Your code here
   Node* temp=node;
    while(node!=NULL){
        temp=temp->next;
       node->data = temp->data;
       if(temp->next!=NULL)
         node=node->next;
        else
        {
            node->next=NULL;
            break;
        }
    }
    
}

Comments

Popular posts from this blog

Intersection point in Y shaped linked list

Multiply Two linked list