Leetcode—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.
【题目大意】:给出且仅给出链表中要删除的某一个结点,删除它
【解法】:将当前节点的下一个节点的值复制到当前节点,然后就可以删除下一个节点了。(相当于删除了当前节点)
【AC代码】:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void deleteNode(struct ListNode* node) {
if(node -> next != NULL){
struct ListNode * temp = node -> next;
node->val = temp->val;
node->next = temp->next;
free(temp);
}
}
本文介绍了一种特殊的链表节点删除方法,即仅通过给定待删除节点来实现删除操作,而非传统的方式。具体实现是将当前节点的值替换为下一个节点的值,再删除下一个节点。
994

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



