20221101数据结构与算法之线性表——单链表OJ

时间:2022-11-01 14:58:29

20221101数据结构与算法之线性表——单链表OJ

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/


struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* prev = head;
struct ListNode* cur = head;
while(cur)
{
if(cur->val == val)
{
//头删
if(cur == head)
{
head = cur->next;
free(cur);
cur = head;
}
else
{
//中间删除
prev->next = cur->next;
free(cur);
cur = prev->next;
}
}
else
{
//不相同则前进
prev = cur;
cur = cur->next;
}
}
return head;
}