移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
Fanxt_Ja1 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 小时前
【数据结构】二叉树的概念
数据结构·二叉树
散11215 小时前
01数据结构-01背包问题
数据结构
消失的旧时光-194315 小时前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww15 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚17 小时前
[数据结构] 排序
数据结构
_不会dp不改名_19 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
睡不醒的kun19 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌19 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long20 小时前
【数据结构】深入理解堆:概念、应用与实现
数据结构