移除链表元素

法一:在原链表上删除

cpp 复制代码
struct SListNode* removeElements(struct SListNode* head, int val)
{
    if (head == NULL)
        return NULL;
    while (head->data == val)
    {
        struct SListNode* del = head;
        head = del->next;
        free(del);
        del = NULL;
        if (head == NULL)
            break;
    }
    if (head == NULL)
        return NULL;
    struct SListNode* cur = head;
    
    while (cur->next != NULL)
    {
        if (cur->next->data == val)
        {
            struct SListNode* del = cur->next;
            cur->next = del->next;
            free(del);
            del = NULL;
        }
        else
        {
            cur = cur->next;
        }
    }
    return head;
}

法二:创建新的链表

cpp 复制代码
struct SListNode* removeElements(struct SListNode* head, int val)
{
    struct SListNode* pcur = NULL, * pend = NULL;
    struct SListNode* cur = head;
    if (cur == NULL)
        return NULL;
    else
    {
        while (cur != NULL)
        {
            if (cur->data != val)
            {
                if (pcur == NULL)
                    pcur = pend = cur;
                else
                {
                    pend->next = cur;
                    pend = cur;
                }
            }
            cur = cur->next;
        }
        if (pend != NULL)
            pend->next = NULL;
        head = pcur;
        return head;
    }
}
相关推荐
沉默金鱼12 分钟前
读书笔记——U3D高级编程:主程手记——第二章2.2List底层源码
数据结构·list
故事和你911 小时前
洛谷-算法2-1-前缀和、差分与离散化1
开发语言·数据结构·c++·算法·深度优先·动态规划·图论
田梓燊8 小时前
力扣:19.删除链表的倒数第 N 个结点
算法·leetcode·链表
阿豪学编程10 小时前
面试题map/unordered相关
数据结构
武藤一雄10 小时前
19个核心算法(C#版)
数据结构·windows·算法·c#·排序算法·.net·.netcore
梦想的颜色11 小时前
mongoTemplate + Java 增删改查基础介绍
数据结构·数据库·mysql
叶小鸡13 小时前
小鸡玩算法-力扣HOT100-堆
数据结构·算法·leetcode
LUVK_14 小时前
第七章查找
数据结构·c++·考研·算法·408
khalil102014 小时前
代码随想录算法训练营Day-31贪心算法 | 56. 合并区间、738. 单调递增的数字、968. 监控二叉树
数据结构·c++·算法·leetcode·贪心算法·二叉树·递归
数智化精益手记局16 小时前
人员排班管理软件的自动化功能解析:解决传统手工人员进行排班管理耗时长的难题
运维·数据结构·人工智能·信息可视化·自动化·制造·精益工程