这道题目不能用go语言写答案,所以用了C语言
题目
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;
* struct ListNode *next;
* };
*/
void deleteNode(struct ListNode* node) {
if (NULL == node) {
return;
}
node->val = node->next->val;
node->next = node->next->next;
}
网友评论