移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

示例 1:

输入:head = 1,2,6,3,4,5,6, val = 6

输出:1,2,3,4,5

示例 2:

输入:head = \[\], val = 1

输出:\[\]

示例 3:

输入:head = 7,7,7,7, val = 7

输出:\[\]

方法:传统求解

利用传统的方法遍历各个节点,判断节点的数据是否为VAL

方法:

struct ListNode* prev = NULL; //删除需要prev和cur

struct ListNode* cur = head;

//逻辑为:prev->next == next

新建两个结构体指针,通过prev->next == next串联起整个链表。

需要注意的是:此方法需要额外注意头删!(prev是空指针,不可以解引用)

头删时,head需要后移一个节点。

cpp 复制代码
struct ListNode* removeElements(struct ListNode* head, int val) {

   

    struct ListNode* prev = NULL;   //删除需要prev和cur

    struct ListNode* cur = head;

        //逻辑为:prev->next == next

    while(cur)

    {

        if(cur->val == val)

        {

            if(prev){

            prev->next = cur->next; //②         //prev最开始是空指针,不能解引用(->)

            free(cur);

            cur = prev->next;   // ①

            //通过①②语句,链接起整个链表;

            }

            else{

                head = cur->next;

                free(cur);

                cur = head;

            }




        }

        else

        {

            prev = cur;

            cur = cur->next;

        }

    }



    return head;

   

}
相关推荐
GrowthDiary00740 分钟前
算法题:寻找二维数组top k问题
数据结构·python·算法
SHARK_pssm1 小时前
【数据结构——栈】
数据结构
阿米亚波1 小时前
【C++ STL】std::unordered_multiset
开发语言·数据结构·c++·笔记·stl
-dzk-2 小时前
【链表】LC 160.相交链表
数据结构·链表
AKA__Zas3 小时前
芝士算法(前缀和2.0)
java·数据结构·算法·leetcode·哈希算法·学习方法
mifengxing3 小时前
Java 集合进阶(一)
java·开发语言·数据结构·复习笔记
risc1234565 小时前
序列化框架
数据结构
MIngYaaa5205 小时前
2026暑期牛客多校1 2026-7-17
数据结构·算法
wabs6665 小时前
关于图论【卡码网107.寻找存在的路线的思考】
数据结构·算法·图论
冻柠檬飞冰走茶7 小时前
PTA基础编程题目集 7-34 通讯录的录入与显示(C语言实现)
c语言·开发语言·数据结构·算法