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 -> 4after calling your function.
class Solution {
public:
void deleteNode(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
};C++
void deleteNode(ListNode* node) {
*node = *node->next;
}
But better properly delete the next node:
void deleteNode(ListNode* node) {
auto next = node->next;
*node = *next;
delete next;
}
本文介绍了一种在单链表中删除指定节点(除尾节点外)的方法,仅需访问该节点即可实现删除操作。提供了C++实现代码示例,包括直接覆盖节点值和正确释放内存的两种方式。
1005

被折叠的 条评论
为什么被折叠?



