题目:
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.
解法:
思路很简单,直接将需要删掉的当前的节点的val值改为它的next节点的值,然后将它的next节点设置为它的next节点的next节点即可,在改变完成后可以把无用的next节点删除,以免后来在用到这块内存的时候会导致不必要的错误,或者赋值为空也可以
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode *tmp = node->next;
node->val = node->next->val;
node->next = node->next->next;
delete tmp;
}
};