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.
A trick applies to this problem. The linkedList should be changeable. Otherwise, there is no way....
void deleteNode(ListNode* node) {
ListNode* nextNode = node->next;
node->val = nextNode->val; // copy the value to the former one.
node->next = nextNode->next; // get ride of next node which has the same value as the former one now.
free(nextNode); // remember to free it in case it was dynamically allocated.
}
本文介绍了一种技巧,可以在仅访问目标节点的情况下删除单链表中的指定节点(非尾节点)。通过将目标节点的值替换为下一个节点的值,并调整指针指向来实现删除操作。
1017

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



