移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
2601_9622017231 分钟前
Java进阶,集合,Colllection,常见数据结构
java·数据结构·windows
挽星安44 分钟前
2026/8/29
数据结构·算法
positive_zpc1 小时前
进阶数据结构图——最短路径(二)
数据结构·算法·图论·最短路径
positive_zpc1 小时前
进阶数据结构图——最小生成树(一)
数据结构·算法·图论
码完就睡1 小时前
数据结构——遍历二叉树
数据结构·算法
老王爱玩车2 小时前
关于函数递归的优缺点分析
开发语言·数据结构·学习·算法
lv__pf2 小时前
Mysql索引优化实战1【TL mysql4】
数据结构
boxiansheng1632 小时前
通讯录系统报错(二)
c语言·数据结构
纪念 2293 小时前
数据结构排序(一)
数据结构·算法·排序算法
Thomas214312 小时前
Java scala 数组 链表
java·链表·scala