237. 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.
分析:因为删除结点本来的步骤是找到当前结点的前一个结点,然后修改前一个结点的 next 指针指向。现在只知道当前要删除的结点,而不知道要删除结点的前一个结点,所以可以通过修改当前要删除结点的值,然后将当前结点指针指向 next 的 next (也就是变成了把后一个结点的值赋给当前结点,然后删除要删除结点的下一个结点),达到删除结点的目的~
1 2 3 4 5 6 7 |
class Solution { public: void deleteNode(ListNode* node) { node->val = node->next->val; node->next = node->next->next; } }; |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼