移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
苏宸啊5 小时前
链式二叉树基操代码实现&OJ题目
数据结构
风筝在晴天搁浅5 小时前
hot100 25.K个一组翻转链表
数据结构·链表
小十一再加一5 小时前
【初阶数据结构】栈和队列
数据结构
长安er6 小时前
LeetCode136/169/75/31/287 算法技巧题核心笔记
数据结构·算法·leetcode·链表·双指针
_w_z_j_7 小时前
最小栈(栈)
数据结构
fufu03117 小时前
Linux环境下的C语言编程(四十八)
数据结构·算法·排序算法
爱装代码的小瓶子8 小时前
算法【c++】二叉树搜索树转换成排序双向链表
c++·算法·链表
思成Codes8 小时前
数据结构:基础线段树——线段树系列(提供模板)
数据结构·算法
卜锦元11 小时前
Golang后端性能优化手册(第三章:代码层面性能优化)
开发语言·数据结构·后端·算法·性能优化·golang
2401_8414956412 小时前
【LeetCode刷题】打家劫舍
数据结构·python·算法·leetcode·动态规划·数组·传统dp数组