203. 移除链表元素
难度简单1230收藏分享切换为英文接收动态反馈
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:

输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1 输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7 输出:[]
提示:
- 列表中的节点数目在范围 [0, 104]内
- 1 <= Node.val <= 50
- 0 <= val <= 50
带头
```
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val)
{
    //这里设置一个哨兵卫的头节点 会好做一点
    struct ListNode* dummry = (struct ListNode*)malloc(sizeof(struct ListNode));
    dummry->next=head;
    struct ListNode* str = dummry;
    while(str->next!=NULL)
    {
        if(str->next->val==val)
        {
            str->next = str->next->next;
        }
        else
        {
            str=str->next;
        }
    }
    return dummry->next;
}不带头
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val)
{
    if(head==NULL)
    {
        return head;
    }
    //不带头 专门处理一下 头节点是不是val 带头的相当于将头节点作为第二个节点进行判断(也就是对所有节点进行统一的处理)
    struct ListNode*str=head;
    struct ListNode*cur=head;
    // while(head!=NULL&&head->val==val)
    // {
    //     head=head->next;
    // }
    while(str!=NULL&&head!=NULL)
    {
        if(head->val==val)
        {
            head=head->next;
        }
        else
        {
                     if(str->val==val)
        {
            cur->next=str->next;
            str=str->next;
        }
        else
        {
            cur=str;
            str=str->next;
        }
        }
    }
    return head;
}尾部插入 将不是val的节点连接到 一个指针上返回这个指针
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val)
{
    struct ListNode* tail = NULL;
    struct ListNode* newnode=NULL;
    while(head!=NULL)
    {
        if(head->val!=val)
        {
            if(tail==NULL)
            {
                newnode=tail=head;
            }
            else
            {
                tail->next=head;
                tail=tail->next;
            }
        }
        head=head->next;
        if(tail!=NULL)
            tail->next=NULL;
    }
    return newnode;
}上面就是这道题的讲解`~



















