移除链表元素

给你一个链表的头节点 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;

   

}
相关推荐
夏末秋也凉26 分钟前
力扣-回溯-491 非递减子序列
数据结构·算法·leetcode
老菜鸡mou2 小时前
[OD E 100] 生成哈夫曼树
数据结构·c++
01_2 小时前
力扣hot100——反转,环形链表 + 快慢指针总结
算法·leetcode·链表·快慢指针
和光同尘@3 小时前
56. 合并区间 (LeetCode 热题 100)
c语言·开发语言·数据结构·c++·算法·leetcode·职场和发展
CS创新实验室3 小时前
计算机考研之数据结构:大 O 记号
数据结构·考研
wen__xvn4 小时前
每日一题洛谷P1914 小书童——凯撒密码c++
数据结构·c++·算法
BUG 劝退师5 小时前
八大经典排序算法
数据结构·算法·排序算法
小小小白的编程日记6 小时前
List的基本功能(1)
数据结构·c++·算法·stl·list
_Itachi__6 小时前
LeetCode 热题 100 283. 移动零
数据结构·算法·leetcode
柃歌6 小时前
【UCB CS 61B SP24】Lecture 5 - Lists 3: DLLists and Arrays学习笔记
java·数据结构·笔记·学习·算法