LeetCode 237: Delete Node in a Linked List

来源:互联网 发布:网络弱电布线工程报价 编辑:程序博客网 时间:2024/06/02 01:38

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.


这道题很简单,给定一个节点,要求删除当前节点。但是你可能会问,前一个节点指针都没有,怎么删除当前节点啊。这里可以抖机灵,把当前节点赋值为下一个节点,然后下一个节点就被抛弃了。等价于把当前节点删除了:
删除节点2之前:

这里写图片描述

将节点2赋值为节点3:

这里写图片描述

这就等于把原来的节点2删掉了。

AC CODE:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */void deleteNode(struct ListNode* node) {    if(node->next == NULL) return; //注意最后一个节点是删不掉的    node->val = node->next->val;    node->next = node->next->next;}
0 0
原创粉丝点击