[leetcode] 237. Delete Node in a Linked List

来源:互联网 发布:网络大电影审批流程 编辑:程序博客网 时间:2024/04/29 17:26

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 is1 -> 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.

这道题是给定链表中指定节点,删除它,题目难度为easy。

如果要删除这个特定节点需要修改前一节点的next指针,但是我们无法取到前一节点,所以这里修改待删除节点的值为后一节点值,然后删除后一节点。至于释放内存,这里不做处理,相信在具体应用环境中大家都会注意到。具体代码:

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

0 0
原创粉丝点击