移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
tekin1 小时前
Python 高级数据结构操作全解析:从理论到实践
数据结构·python·集合set·高级数据结构·集合操作·队列操作·堆操作
居然有人6543 小时前
23贪心算法
数据结构·算法·贪心算法
重生之我是冯诺依曼3 小时前
数据结构绪论
数据结构
h^hh4 小时前
洛谷 P3405 [USACO16DEC] Cities and States S(详解)c++
开发语言·数据结构·c++·算法·哈希算法
重生之我要成为代码大佬4 小时前
Python天梯赛10分题-念数字、求整数段和、比较大小、计算阶乘和
开发语言·数据结构·python·算法
Dreams°1234 小时前
【透过 C++ 实现数据结构:链表、数组、树和图蕴含的逻辑深度解析】
开发语言·数据结构·c++·mysql
wanjiazhongqi5 小时前
链表和STL —— list 【复习笔记】
数据结构·c++·笔记·链表
Suk-god5 小时前
【Redis原理】底层数据结构 && 五种数据类型
数据结构·数据库·redis
Distance失落心5 小时前
java基于数组实现队列(四)
java·开发语言·数据结构·算法·面试·java-ee·intellij-idea
MZWeiei7 小时前
PTA:有序顺序表的插入
数据结构