移除链表元素

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

   

}
相关推荐
AlenTech4 小时前
160. 相交链表 - 力扣(LeetCode)
数据结构·leetcode·链表
会周易的程序员4 小时前
多模态AI 基于工业级编译技术的PLC数据结构解析与映射工具
数据结构·c++·人工智能·单例模式·信息可视化·架构
sin_hielo4 小时前
leetcode 1161(BFS)
数据结构·算法·leetcode
一起努力啊~4 小时前
算法刷题-二分查找
java·数据结构·算法
iAkuya6 小时前
(leetcode)力扣100 34合并K个升序链表(排序,分治合并,优先队列)
算法·leetcode·链表
我是小狼君6 小时前
【查找篇章之三:斐波那契查找】斐波那契查找:用黄金分割去“切”数组
数据结构·算法
放荡不羁的野指针7 小时前
leetcode150题-字符串
数据结构·算法·leetcode
bubiyoushang8887 小时前
MATLAB比较SLM、PTS和Clipping三种算法对OFDM系统PAPR的抑制效果
数据结构·算法·matlab
C雨后彩虹8 小时前
计算误码率
java·数据结构·算法·华为·面试
不染尘.8 小时前
进程切换和线程调度
linux·数据结构·windows·缓存