题目:
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.
思路:
初步看这道题目觉得不可能,因为你不知道它的前驱结点是什么。后来才发现可以通过一种比较“流氓”的方法实现:我们将它的后继结点的值赋给它,然后删除它的后记结点即可。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode* next_node = node->next;
node->val = next_node->val;
node->next = next_node->next;
delete next_node;
}
};