237. Delete Node in a Linked List
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.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node)
{
//way-1
/*
ListNode*p = node;
ListNode*last_p;
while (p->next)
{
p->val = p->next->val;
last_p = p;
p = p->next;
}
last_p->next = NULL;
delete(p);
*/
//way-2
ListNode*p = node->next;
node->val = p->val;
node->next = p->next;
delete(p);
}
};
本文介绍了一种在单链表中删除指定节点(除尾节点外)的方法,仅需访问该节点。通过两种方式实现:一是遍历并更新节点值直至最后一个节点;二是直接覆盖当前节点值并跳过下一个节点。
1012

被折叠的 条评论
为什么被折叠?



