移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
JeffersonZU1 小时前
【数据结构】2-3-1单链表的定义
数据结构·链表
JeffersonZU1 小时前
【数据结构】1-4算法的空间复杂度
c语言·数据结构·算法
L_cl2 小时前
【Python 算法零基础 4.排序 ① 选择排序】
数据结构·算法·排序算法
无聊的小坏坏2 小时前
【数据结构】二叉搜索树
数据结构
丁一郎学编程5 小时前
优先级队列(堆)
java·数据结构
Codeking__5 小时前
前缀和——中心数组下标
数据结构·算法
GG不是gg6 小时前
数据结构:二叉树一文详解
数据结构·青少年编程
花火QWQ6 小时前
图论模板(部分)
c语言·数据结构·c++·算法·图论
姬公子5217 小时前
leetcodehot100刷题——排序算法总结
数据结构·c++·算法·排序算法
Ronin3058 小时前
【C++】18.二叉搜索树
开发语言·数据结构·c++