0
点赞
收藏
分享

微信扫一扫

【 LeetCode题解 】203. 移除链表元素


【 LeetCode题解 】203. 移除链表元素

题目链接 : https://leetcode.cn/problems/remove-linked-list-elements/ 博客主页链接:Duck Bro 博客主页 关注博主,后期持续更新系列文章
***感谢观看,希望对你有所帮助***


目录

  • 【 LeetCode题解 】203. 移除链表元素
  • 🌟题目要求
  • 🌟解题思路(动图解析)
  • 🧐方案一
  • 😁方案二
  • 🌟代码示列


🌟题目要求

【 LeetCode题解 】203. 移除链表元素_算法

🌟解题思路(动图解析)

🧐方案一

方案1:主要思路遇到val就删除,分为头删和中间删除两种情况。

当val在链表中间时,遇到val就删除链表中和val相同的节点,并链接val后面的节点。

当val在链表开头时,或者连续的时候,我们将链表其实的head(头)向后移动,直到找到不是val的节点,作为开始的头。

【 LeetCode题解 】203. 移除链表元素_数据结构_02

【 LeetCode题解 】203. 移除链表元素_c语言_03

😁方案二

方案2:遍历原链表,把不是val的节点,尾插到新链表

使用尾插的方法,将不是val的值插入到新链表,为了避免增加时间复杂度,使用tail为尾节点
但需要注意的是当末尾不是val值时需要将tail->next置为NULL

【 LeetCode题解 】203. 移除链表元素_数据结构_04

🌟代码示列

方案一 代码:

struct ListNode* removeElements(struct ListNode* head, int val)
{
        struct ListNode*prev=NULL;
        struct ListNode*cur=head;
        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*newhead=NULL;
    struct ListNode*tail=NULL;
    while(cur)
    {
        if(cur->val==val)
        {
            struct ListNode* del=cur;        
            cur=cur->next;  
            free(del);
        }
        else
        {
            if(tail == NULL)
            {
                newhead = tail = cur;
            }
            else
            {
                tail->next=cur;
                tail=tail->next;
            }
            cur=cur->next;
            
        }
    }    
        if(tail)
            tail->next=NULL;     
       
     return newhead;
}

举报

相关推荐

0 条评论