移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
小手cool16 小时前
二分查找:在有序数组中查找最接近 target 的元素索引
java·数据结构·算法
zmzb010316 小时前
C++课后习题训练记录Day216
数据结构·c++·算法
天威?*18 小时前
团体程序设计天梯练习集L3-001 凑零钱
数据结构·c++
龙砚序19 小时前
【数据结构|栈实战 03-2】不带头结点链栈实现:文本编辑器撤销 Undo 模块(C 语言)
数据结构
hai31524754319 小时前
阶乘分层关系模型存储文本与表格
数据结构·算法·rust·排序算法·线性回归
小白的高手之路19 小时前
【LeetCode 热题 100】206. 反转链表|链表、迭代、递归(Python)
笔记·python·算法·leetcode·链表·职场和发展·力扣
凌冰_20 小时前
数据结构 - 数组(八)
数据结构·算法·矩阵
Shaoshing21 小时前
LeetCode 1798. 你能构造出连续值的最大数目
java·数据结构·算法
YSL07012421 小时前
C++string类详解
开发语言·数据结构·c++
大今野21 小时前
江苏专转本计算机大类基础理论考点:算法的概念与复杂度分析
数据结构·算法·专转本