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.
解法1:O(1) Time
由于只给了当前node的指针,那么没办法得到前面一个节点的信息。只能换种思考方式。我们可以将下一个节点的数值拷贝过来然后删除下一个节点就可以。
C++
要注意的是要删除下一个节点指针对应的object,否则会造成leak
Java
|