移除链表元素_每日一题

"路虽远,行则将至"

❤️主页:小赛毛****

☕今日份刷题:移除链表元素

题目描述:

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

题目分析:

这里需要注意一点的是:在oj题目里面如果没有提到带哨兵位,则默认为不带头结点的链表。

题解代码:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


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

现在,我们再来考虑一种解法:

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

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* removeElements(struct ListNode* head, int val)
{
    struct ListNode* cur = head;
    struct ListNode* newhead = NULL,*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;
}
相关推荐
晚枫~27 分钟前
图论基础:探索节点与关系的复杂网络
网络·数据结构·图论
liu****43 分钟前
20.哈希
开发语言·数据结构·c++·算法·哈希算法
夏鹏今天学习了吗1 小时前
【LeetCode热题100(47/100)】路径总和 III
算法·leetcode·职场和发展
smj2302_796826521 小时前
解决leetcode第3721题最长平衡子数组II
python·算法·leetcode
m0_626535202 小时前
力扣题目练习 换水问题
python·算法·leetcode
第六五2 小时前
DPC和DPC-KNN算法
人工智能·算法·机器学习
一匹电信狗2 小时前
【LeetCode_160】相交链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
Java技术实践2 小时前
JPA 用 List 入参在 @Query中报错 unexpected AST node: {vector}
数据结构·windows·list
陌路202 小时前
S4双向链表
数据结构·链表
再卷也是菜2 小时前
C++篇(14)二叉树进阶算法题
c++·算法