其他分享
首页 > 其他分享> > 【LeetCode】203. 移除链表元素

【LeetCode】203. 移除链表元素

作者:互联网

Q:

给你一个链表的头节点 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
输出:[]

S:

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val){
    if(head==NULL)
        return NULL;
    struct ListNode* tail=head;
    struct ListNode* prev=NULL;
    while(tail)
    {
        if(tail->val==val)
        {
            //头删
            if(tail==head)
            {
                head=tail->next;
                free(tail);
                tail=head;
            }
            //中间删
            else
            {
                prev->next=tail->next;
                free(tail);
                tail=prev->next;
            }
        }
        else
        {
            prev=tail;
            tail=tail->next;
        }
    }
    return head;
}

标签:203,ListNode,struct,val,head,next,链表,tail,移除
来源: https://blog.csdn.net/m0_51350326/article/details/120935092