当前位置: 首页 > news >正文

leetcode203.移除链表元素

目录

  • 问题描述
  • 示例
    • 提示
  • 具体思路
    • 思路一
    • 思路二
  • 代码实现

问题描述

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

题目链接:移除链表元素

示例

在这里插入图片描述

在这里插入图片描述

提示

  列表中的节点数目在范围 [0, 1 0 4 10^4 104] 内
  1 <= Node.val <= 50
  0 <= val <= 50

具体思路

思路一

  通过查找链表中节点的值不等于val,就在新的链表上进行尾插,不过这种方式实现的时间复杂度也比较高

思路二

  通过遍历链表,查找链表中的值等于val就进行删除,将前一个节点(pre)的next指针指向它后一个节点,然后free掉当前节点(cur),然后再将当前节点的指针(cur)指向下一个节点
在这里插入图片描述

代码实现

//思路1
/*** Definition for singly-linked list.* struct ListNode {*     int val;*     struct ListNode *next;* };*/
struct ListNode* removeElements(struct ListNode* head, int val) {struct ListNode* cur = head;struct ListNode* newhead=NULL;struct ListNode* tail=NULL;while(cur){if(cur->val!=val){if(tail==NULL){newhead=tail=cur;}else{tail->next=cur;tail=tail->next;}cur=cur->next;tail->next=NULL; }else{struct ListNode* del =cur;cur=cur->next;free(del);}}return newhead;
}
//思路2
/*** Definition for singly-linked list.* struct ListNode {*     int val;*     struct ListNode *next;* };*/
struct ListNode* removeElements(struct ListNode* head, int val) {struct ListNode* prev =NULL;struct ListNode* cur = head;while(cur){if(cur->val==val){if(prev){prev->next=cur->next;free(cur);cur =prev->next;}else{cur=head->next;free(head);head=cur;}}else{prev=cur;cur=cur->next;}}return head;
}

http://www.mrgr.cn/news/91693.html

相关文章:

  • 【Java】泛型与集合篇 —— 泛型
  • SCANet代码解读
  • 【Elasticsearch】`nested`和`flattened`字段在索引时有显著的区别
  • 【DeepSeek系列】04 DeepSeek-R1:带有冷启动的强化学习
  • TCP和Http协议
  • PyTorch 源码学习:阅读经验 代码结构
  • 嵌入式音视频开发(三)直播协议及编码器
  • 【Java】泛型与集合篇 —— Set 接口
  • 前端常见面试题-2025
  • C语言——时基
  • Linux-----进程(多任务)
  • C#发送邮件
  • 基于正则化密集连接金字塔网络的显著实例分割
  • mysql总结
  • Day6 25/2/19 WED
  • Windows 启动 SSH 服务报错 1067
  • Compose 常用UI组件
  • PVE使用一个物理网卡采用VLAN为管理IP和VM分配网络的问题
  • springboot-ffmpeg-m3u8-convertor nplayer视频播放弹幕 artplayer视频弹幕
  • 【SQL】多表查询案例