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)将后一节点的val赋给当前节点,然后删除后一节点。
2)将后一节点整体赋给当前节点,*node访问node指针所指内存。
class Solution {
public:
/*void deleteNode(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}*/
void deleteNode(ListNode* node) {
*node = *(node->next); //node是一指针,指向一内存,*node就会访问该内存的值.
}
};