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.
例:1 -> 2 -> 3 -> 4 -> 5
若要删除第3个节点(3),由于不能获得即将删除的节点的前一个节点(2),故先copy下一个节点的值,使链表如下:1 -> 2 -> 4' ->4 -> 5
然后只需要删除第4个节点即:
1 -> 2 -> 4' -> 5
(16ms)
/**
* 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) {
node->val = node->next->val;
node->next = node->next->next;
}
};