移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
流年如夢11 小时前
单链表进阶版 -->双向链表
数据结构·链表
流年如夢12 小时前
单链表 -->增、删、查、改等详细操作
c语言·数据结构
handler0115 小时前
【算法模板】最小生成树:稠密图选 Prim,稀疏图选 Kruskal
c语言·数据结构·c++·算法
此生决int15 小时前
快速复习之数据结构篇——栈和队列
数据结构·c++
昵称小白15 小时前
子串专题部分
数据结构·算法·哈希算法
ShoreKiten17 小时前
cpp考前急救
数据结构·c++·算法
诙_17 小时前
C++数据结构--AVL树
数据结构
Cando学算法18 小时前
欧拉回路(一笔画)
数据结构·c++·图论
图码19 小时前
一文搞懂如何判断字符串是否为Pangram(全字母句)
数据结构·算法·网络安全·数字雕刻·ping++
khalil102019 小时前
代码随想录算法训练营Day-43 动态规划10 | 300.最长递增子序列、674. 最长连续递增序列、718. 最长重复子数组
数据结构·c++·算法·leetcode·动态规划·子序列问题