LeetCode 237. Delete Node in a Linked List

来源:互联网 发布:unity3d c 脚本教程 编辑:程序博客网 时间:2024/06/05 16:39

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 (也就是变成了把后一个结点的值赋给当前结点,然后删除要删除结点的下一个结点),达到删除结点的目的。

class Solution {public:    void deleteNode(ListNode* node) {        node->val = node->next->val;        node->next = node->next->next;    }};


0 0
原创粉丝点击