移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
菜鸟233号31 分钟前
力扣669 修剪二叉搜索树 java实现
java·数据结构·算法·leetcode
SadSunset2 小时前
力扣题目142. 环形链表 II的解法分享,附图解
算法·leetcode·链表
jingfeng5143 小时前
哈希表的概念+实现
数据结构·哈希算法·散列表
ホロHoro4 小时前
数据结构非线性部分(1)
java·数据结构·算法
沉下去,苦磨练!4 小时前
实现二维数组反转
java·数据结构·算法
玖剹4 小时前
哈希表相关题目
数据结构·c++·算法·leetcode·哈希算法·散列表
红豆诗人4 小时前
数据结构初阶知识--单链表
c语言·数据结构
L_09075 小时前
【C++】高阶数据结构 -- 二叉搜索树(BST)
数据结构·c++
仰泳的熊猫5 小时前
1150 Travelling Salesman Problem
数据结构·c++·算法·pat考试
lixzest6 小时前
C++中经常用的头文件介绍
数据结构·c++·算法