14
Delete a node in the middle of a single linked list
Linked-list
C

Given a linkedlist, for example:-

Input:- A->B->C->D->E

you have to delete node C.

Constrain :- You have only access to the node to be deleted (node C).

Output :- A->B->D->E

Algorithms:-

1) Take a temp node and point it to the next to the accessible node. (i.e in our case temp node pointing to node D)

2) Copy data of temp node to accessible node. (i.e copy data of node D to node C)

3) Now linked accessible node to next node of temp. (i.e link node C to node E).

If we look at the result of above algorithm, in actual node D is got deleted (if we see it node wise) but if we look it linkedlist data wise then it appears node C got deleted.

bool deleteNode(linkedList *c)
{
        linkedList *temp;
        if (c->next == NULL || c == NULL)
                return false;
        temp = c->next;
        c->data = temp->data;
        c->next = temp->next;
        return true;
}

Note:- This problem can not be solved if node to be deleted is the last node in the linkedlist.

Author

Notifications

?