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 == NULL || node->next == NULL) return;
node->val = node->next->val;
node->next = node->next->next;
}
};

本文介绍了一种在单链表中删除指定节点的方法,该方法仅使用指向待删除节点的指针,通过交换当前节点和下一节点的数据来实现,适用于除尾节点外的所有情况。
1016

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



