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.
假设链表为1 -> 2 -> 3 -> 4
,给出第三个要删除的节点其值为3,调用函数后链表为1 -> 2 -> 4。
分析:
只需要将待删除节点的后一个节点值移到待删除节点,然后删除后一个节点即可。
class Solution {
public:
void deleteNode(ListNode* node) {
if(!node)
{
return;
}
ListNode *temp = node->next;
node->val = node->next->val; //将下一节点的值填充到该节点
node->next = node->next->next; //删除下一个节点
delete temp;
return;
}
};