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.
题解:这道题的意思是向函数传入链表的某一节点,然后将其删除掉。这里和以前不一样的地方在于,可以通过头指针遍历到需要删除的节点位置,而这道题只给了需要删除的节点的位置,但是同样的,只是需要将当前的节点A的下一节点B替换掉当前节点A,再free掉B节点即可。
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ void deleteNode(struct ListNode* node) { struct ListNode *p = node->next; if(!node) return; memcpy(node, node->next, sizeof(struct ListNode)); free(p); }
对于free();
如果p 是NULL 指针,那么free 对p 无论操作多少次都不会出问题。如果p 不是NULL 指针,那么free 对p连续操作两次就会导致程序运行错误。