移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
月盈缺4 小时前
学习嵌入式的第二十二天——数据结构——双向链表
数据结构·学习·链表
科大饭桶6 小时前
C++入门自学Day14-- Stack和Queue的自实现(适配器)
c语言·开发语言·数据结构·c++·容器
躲在云朵里`7 小时前
深入理解数据结构:从数组、链表到B树家族
数据结构·b树
1白天的黑夜110 小时前
链表-24.两两交换链表中的结点-力扣(LeetCode)
数据结构·leetcode·链表
养成系小王16 小时前
四大常用排序算法
数据结构·算法·排序算法
闪电麦坤9517 小时前
数据结构:从前序遍历序列重建一棵二叉搜索树 (Generating from Preorder)
数据结构··二叉搜索树
闪电麦坤9517 小时前
数据结构:二叉树的遍历 (Binary Tree Traversals)
数据结构·二叉树·
球king17 小时前
数据结构中邻接矩阵中的无向图和有向图
数据结构
野渡拾光19 小时前
【考研408数据结构-05】 串与KMP算法:模式匹配的艺术
数据结构·考研·算法
pusue_the_sun1 天前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树