📜  门| GATE-CS-2004 |第 32 题(1)

📅  最后修改于: 2023-12-03 15:28:41.997000             🧑  作者: Mango

GATE-CS-2004 Question 32

This question from GATE-CS-2004 is a coding question related to Linked Lists in C. The question asks us to implement C code to delete a node from a singly linked list based on a given condition.

Question Details

The full question is:

Write a C function to delete a node from a singly linked list, given only a pointer to that node. Explain why this method cannot be used to delete the last node of the list.

Solution

Here is one possible solution to this question:

void delete_node(struct node *ptr)
{
    struct node *temp;
    if (ptr == NULL || ptr->next == NULL)
    {
        return;
    }
    else
    {
        temp = ptr->next;
        ptr->data = temp->data;
        ptr->next = temp->next;
        free(temp);
    }
}

This function takes in a pointer to a node in the linked list and deletes that node, by copying the data of the next node into the current node and then deleting the next node. If there is no next node, the function simply returns without doing anything.

However, this function cannot be used to delete the last node of the list because there is no node after the last node to copy data from. To delete the last node, we need a pointer to the previous node as well, so that we can set its "next" pointer to NULL. Without this pointer, we would end up with a dangling pointer that points to memory that has been freed, which can cause undefined behavior in the future.

Explanation

The solution uses a temporary pointer to the next node to copy the data of the next node into the current node. Then it frees the memory allocated to the next node. This effectively removes the current node from the list.

However, this method cannot be used to delete the last node of the list because there is no node after the last node to copy data from. Therefore, if we try to use this method to delete the last node, the "next" pointer of the previous node will still point to the last node, which has been freed. This can result in undefined behavior in future operations that use this pointer.

Therefore, to delete the last node, we need to use a different method that involves keeping a pointer to the previous node as well, so that we can properly update its "next" pointer to NULL.