移除链表元素
删除链表中等于给定值 val 的所有节点。
例如:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* cur = head;
struct ListNode* per = NULL;
while (cur) {
if (cur->val == val) {
struct ListNode* next = cur->next;
if (cur == head) {
head = next;
}
else {
per->next = next;
}
free(cur);
cur = next;
}
else {
per = cur;
cur = cur->next;
}
}
return head;
}
本文介绍如何在C语言中编写代码来删除链表中所有值等于给定值val的节点。通过遍历链表并更新指针,可以有效地移除这些节点。
1025

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



