题目
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
思路
单链表要删除,必须知道要删除结点的前一个结点。但此题困难在于只给了要删除结点的引用,而无法获知该g结点的前一个结点,因此按传统方法无法删除。
但这题其实非常简单,换种思路,我们把删除该结点改为删除该结点的下一个结点,但在删除之前把下一个结点的值覆盖此结点的值。因此,虽然物理上删除的是下一个结点,但实际上该结点的值已经被删除了,而下一个结点的值仍然保留下来。
代码
|
|