移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
凉茶钱1 小时前
【数据结构】C语言实现队列
c语言·数据结构
zander2582 小时前
34. 在排序数组中查找元素的第一个和最后一个位置:用两个边界定位区间
数据结构·算法·leetcode
乐观勇敢坚强的老彭18 小时前
C++信奥静态数组和动态数组
数据结构·c++·算法
旖旎夜光19 小时前
LeetCode 991: 坏了的计算器(贪心算法) —— 题解
数据结构·c++·算法·leetcode·贪心算法
旖旎夜光19 小时前
LeetCode 553:最优除法(贪心算法) —— 题解
数据结构·c++·算法·leetcode·贪心算法
雾喔19 小时前
算法练习7
java·数据结构·算法
XiaoYu1__21 小时前
数据结构进阶·其二:用简洁的树状数组处理动态区间问题及两种常见变形
数据结构·c++·笔记·算法·树状数组
Keven_111 天前
算法札记:二叉树前序、中序、后序遍历及对应序列重要性质
数据结构·算法·深度优先
如此这般英俊1 天前
手搓Claude Code-第十章 system_prompt
数据结构·人工智能·python·语言模型·自然语言处理·prompt
旖旎夜光1 天前
LeetCode 435:无重叠区间(贪心算法) —— 题解
数据结构·c++·算法·leetcode·贪心算法