您的位置:首页 > Web前端 > Node.js

LeetCode 237 Delete Node in a Linked List(技巧)

2017-04-08 11:00 423 查看
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.

题目大意:给出链表中某一节点的指针,删除该节点。
解题思路:刚看到这道题时,我是懵逼的,因为只给出了要删除节点的指针,无法找到该节点的前一个节点,这就不好删除。偷瞄了一眼Solutions发现,原来可以通过将下一个节点的值赋给当前要删除的节点,然后删除当前节点的下一个节点。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
void deleteNode(struct ListNode* node) {
struct ListNode* temp = node->next;
node->val = temp->val;
node->next = temp->next;
free(temp);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode