题目来源:https://leetcode.com/problems/delete-node-in-a-linked-list/
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) {
if(node==nullptr)
return ;
node->val = node->next->val;
node->next = node->next->next;
}
};
本文介绍了一种独特的方法来删除单链表中的指定节点,不依赖于节点的前驱节点。通过直接覆盖该节点的值为下一个节点的值,并跳过下一个节点,实现了高效删除操作。

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



