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.
题目大意:给出链表中某一节点的指针,删除该节点。
解题思路:刚看到这道题时,我是懵逼的,因为只给出了要删除节点的指针,无法找到该节点的前一个节点,这就不好删除。偷瞄了一眼Solutions发现,原来可以通过将下一个节点的值赋给当前要删除的节点,然后删除当前节点的下一个节点。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void deleteNode(struct ListNode* node) {
struct ListNode* temp = node->next;
node->val = temp->val;
node->next = temp->next;
free(temp);
}