移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
黎明smaly5 小时前
【排序】插入排序
c语言·开发语言·数据结构·c++·算法·排序算法
YuTaoShao5 小时前
【LeetCode 热题 100】206. 反转链表——(解法一)值翻转
算法·leetcode·链表
YuTaoShao5 小时前
【LeetCode 热题 100】142. 环形链表 II——快慢指针
java·算法·leetcode·链表
CCF_NOI.5 小时前
(普及−)B3629 吃冰棍——二分/模拟
数据结构·c++·算法
神的孩子都在歌唱6 小时前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
艾莉丝努力练剑8 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
汤姆爱耗儿药13 小时前
专为磁盘存储设计的数据结构——B树
数据结构·b树
许小燚21 小时前
线性表——双向链表
数据结构·链表
qqxhb1 天前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
晚云与城1 天前
【数据结构】顺序表和链表
数据结构·链表