Deleting any node from a single linked list when only pointer to that node is given

前端 未结 6 1052
天涯浪人
天涯浪人 2020-12-08 05:44

This is a question posed to me in an interview.

\"A single linked list is there in the memory. You have to delete a node. You need to write a function to delete that

6条回答
  •  庸人自扰
    2020-12-08 06:17

    Dangling Pointer:

    (http://en.wikipedia.org/wiki/Dangling_reference)

    Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type. These are special cases of memory safety violations.

    Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. As the system may reallocate the previously freed memory to another process, if the original program then dereferences the (now) dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data.

    In your answer, to delete the given node you actually delete the next node, which might be being referenced by a pointer. That's how dangling pointer problem arise.

    (1) There are no outside references to the list, as you clarify in a note. (2) Dangling pointer problem can arise, as the interviewer said.

    Both (1) and (2) cannot be correct at the same time. Which means there is a misunderstanding somewhere.

    About Deleting the Last Node:

    But the interviewer asked me again, what if I pass the address of the last node. I told him, since the next will be a NULL, copy that NULL into the data field along with the address to the next node which is also NULL.

    I think you are confusing these two things: (1) A pointer p that points to NULL, (2) A linked list node that has NULL in its data field.

    Suppose the data structure is a -> b -> c -> d. Writing NULL to d's data field will not magicly make c to have a NULL pointer in its next field.

    You can delete the last node if the linked list always has a special last node that will never be deleted. For example, a -> b -> c -> d -> LAST where LAST has a special value in its data field that denotes it is really the last element. Now to delete d, you could delete LAST and write the special value in d's data field.

    Maybe these are exactly what you tried to tell during the interview, in which case there must have been some miscommunication between you and the interviewer.

提交回复
热议问题