移除链表元素

法一:在原链表上删除

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#
hy.z_7771 小时前
【数据结构刷题】顺序表与ArrayList
数据结构
Felven1 小时前
A. Everybody Likes Good Arrays!
数据结构·算法
稻草猫.4 小时前
【Java 数据结构】List,ArrayList与顺序表
java·数据结构·idea
ゞ 正在缓冲99%…4 小时前
leetcode66.加一
java·数据结构·算法
present--014 小时前
【数据结构】优先级队列
数据结构
代码不停6 小时前
Java数据结构——Stack
java·开发语言·数据结构
奋进的小暄6 小时前
数据结构(java)二叉树的基本操作
java·数据结构·算法
robin_suli6 小时前
链表系列一>两两交换链表中的结点
数据结构·算法·链表
wuqingshun31415915 小时前
蓝桥杯 5. 交换瓶子
数据结构·c++·算法·职场和发展·蓝桥杯