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

Easy-题目5:237. Delete Node in a Linked List

2016-05-30 19:46 429 查看
题目原文:

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.

题目大意:

删除单链表中指定节点。

题目分析:

把指定节点的值改成后面的值,并令其后继节点指向原后继节点的后继节点。

源码:(language:c)

void deleteNode(struct ListNode* node) {
if(node) {
node->val=node->next->val;
node->next=node->next->next;
}
}


成绩:

4ms,beats 0.52% 众数4ms,99.48%

Cmershen的碎碎念:

在数据结构课上,我们删除链表节点的方法是令其前驱节点指向后继节点。可是本题中只有当前节点,又是单链表,无法获得其前驱节点。这个问题困扰了我一段时间,但我发现还有value值可以利用,因此得出上述算法。

其实测试用例不完全,根据源码,Node->next是有可能为空的,再引用val和next有可能引发NPD异常。因此上述的ac代码不可以用于删除链表中最后一个节点。(dts大法好!!!(^__^) 嘻嘻……)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: