法一:在原链表上删除
cpp
struct SListNode* removeElements(struct SListNode* head, int val)
{
if (head == NULL)
return NULL;
while (head->data == val)
{
struct SListNode* del = head;
head = del->next;
free(del);
del = NULL;
if (head == NULL)
break;
}
if (head == NULL)
return NULL;
struct SListNode* cur = head;
while (cur->next != NULL)
{
if (cur->next->data == val)
{
struct SListNode* del = cur->next;
cur->next = del->next;
free(del);
del = NULL;
}
else
{
cur = cur->next;
}
}
return head;
}
法二:创建新的链表
cpp
struct SListNode* removeElements(struct SListNode* head, int val)
{
struct SListNode* pcur = NULL, * pend = NULL;
struct SListNode* cur = head;
if (cur == NULL)
return NULL;
else
{
while (cur != NULL)
{
if (cur->data != val)
{
if (pcur == NULL)
pcur = pend = cur;
else
{
pend->next = cur;
pend = cur;
}
}
cur = cur->next;
}
if (pend != NULL)
pend->next = NULL;
head = pcur;
return head;
}
}