题解 | #删除链表的节点#
删除链表的节点
https://www.nowcoder.com/practice/f9f78ca89ad643c99701a7142bd59f5d
struct ListNode* deleteNode(struct ListNode* head, int val) {
// 添加一个头结点指针
struct ListNode* res = (struct ListNode*)malloc(sizeof(struct ListNode));
res->next = head;
struct ListNode* pre = res; // 前序节点
struct ListNode* cur = head; // 当前节点
while (cur != NULL) {
// 注意:要先进性判断,防止链表第一个值就是 val 的情况
if (cur->val == val) {
pre->next = cur->next; // 跳过,断开连接
cur = cur->next; // 继续循环,删除所有匹配的节点
} else {
pre = cur;
cur = cur->next;
}
}
// 返回了从头节点之后开始的链表。因为 res->next 指向了真正链表的头部
return res->next;
}
