您的位置:首页 > 其它

leetcode 删除单链表指定元素

2015-08-05 18:01 483 查看
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node p.

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.

一开始想到的是已经知道删除节点p之前的节点q,那么:

q->next=p->next;
delete p;


但是题目很明显只给出单链表要删除的节点p,其他信息不知,故不能直接采用上述写法,但是思想还是一致:可以把p下一位值赋给p,然后把p的下一位删除,因为我们已经知道p的下一位的前的节点:

void deleteNode(struct ListNode* node) {
node->val=node->next->val;
node->next=node->next->next;
//delete p;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: