方法1:按部就班删除节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode* prev = NULL;
struct ListNode* cur = head;
while(cur)
{
if(cur->val != val)
{
//prev 和 cur 后移
prev = cur;
cur = cur->next;
}
else
{
if(prev == NULL)
{
//首个节点就是要删除的值
head = cur->next;
free(cur);
cur = head;
}
else
{ //第二个节点之后是需要移除的值
prev->next = cur->next;
free(cur);
cur = prev->next;
}
}
}
return head;
}
方法二:把不是val的值,尾插到新链表
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* newHead = NULL,*tail = NULL;
struct ListNode* cur = head;
while (cur)
{
if (cur->val != val)
{
//尾插
if (tail == NULL)
{
newHead = tail = cur;
}
else
{
tail->next = cur;
tail = tail->next;
}
cur = cur->next;
}
else
{
struct ListNode* next = cur->next;//体前保存下一个
free(cur);//free掉要删除的值
cur = next;
}
}
if (tail)
{
tail->next = NULL;
}
return newHead;
}