0
点赞
收藏
分享

微信扫一扫

Leetcode203.移除链表元素

犹大之窗 2022-05-03 阅读 44

 题目链接

 

struct ListNode* removeElements(struct ListNode* head, int val)
{
    struct ListNode* cur = head;
    struct ListNode* prev=NULL;
    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;

}

代码:

struct ListNode* removeElements(struct ListNode* head, int val)
{
    
    struct ListNode* cur = head;
    struct ListNode* tail= NULL;
    head=NULL;
    while(cur)
    {
        if(cur->val==val)//删除
        {
            struct ListNode* del = cur;//创建新节点
            cur=cur->next;
            free(del);
        }
        else//插入新链表中
        {
            if(tail==NULL)//第一次插入
            {
                head=tail=cur;
            }
            else//后续正常插入
            {
                tail->next=cur;
                tail = tail->next;
            }
            cur = cur->next;
        }
        
    }
    if(tail)//尾部置空
    {
       tail->next=NULL;
    }
    return head;

}
举报

相关推荐

0 条评论