移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
im_AMBER2 小时前
数据结构 09 二叉树作业
数据结构·笔记·学习
l1t3 小时前
利用DeepSeek修改数据结构提升求解集合程序效率
数据结构·python·deepseek
先做个垃圾出来………5 小时前
偏移量解释
数据结构·算法
Dream it possible!5 小时前
LeetCode 面试经典 150_链表_旋转链表(64_61_C++_中等)
c++·leetcode·链表·面试
立志成为大牛的小牛5 小时前
数据结构——三十三、Dijkstra算法(王道408)
数据结构·笔记·学习·考研·算法·图论
小王C语言7 小时前
哈希表实现
数据结构·哈希算法·散列表
靖难都7 小时前
数据结构:单链表
数据结构
perseveranceX8 小时前
插入排序:扑克牌式的排序算法!
c语言·数据结构·插入排序·时间复杂度·排序稳定性
CS创新实验室8 小时前
典型算法题解:长度最小的子数组
数据结构·c++·算法·考研408
Ialand~10 小时前
深度解析 Rust 的数据结构:标准库与社区生态
开发语言·数据结构·rust