移除链表元素

法一:在原链表上删除

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;
    }
}
相关推荐
老师我太想进步了20264 小时前
【数据结构-3】算法美学之降复杂度
数据结构·算法
w_zero_one16 小时前
算法--构造
java·数据结构·算法
lisw0520 小时前
互联网上的数据结构可视化!
数据结构·信息可视化
老师我太想进步了20261 天前
【数据结构-1】例解算法复杂度
数据结构·算法
YSL0701241 天前
一文通关-----排序
数据结构·算法
夜不会漫长2 天前
C++:红黑树
数据结构·算法
冻柠檬飞冰走茶2 天前
PTA刷题集之Airline Routes(C语言实现)
c语言·开发语言·数据结构·算法
736c2 天前
固件开发岗算法
数据结构·算法
冻柠檬飞冰走茶2 天前
PTA刷题集之Battle Over Cities - Hard Version(C语言实现)
c语言·开发语言·数据结构·算法
PaperAccept2 天前
【研知有术论文发表】材料科学一区期刊,影响因子30+的纳米科技SCI,审稿严格但有效率
大数据·数据结构·科技·量子计算