当前位置:网站首页>链表(一)——移除链表元素
链表(一)——移除链表元素
2022-06-28 06:04:00 【木棣%】
给你一个链表的头节点
head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。示例 :
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
提示:
- 列表中的节点数目在范围 [0, 104] 内
- 1 <= Node.val <= 50
- 0 <= val <= 50
思路
迭代
(非虚拟节点)
- 找到该结点的前一个结点,进行删除操作
- 移除头结点和移除其他节点的操作不同
- 将头结点向后移动一位就可以移除该结点
- 头节点和其它节点分开
public ListNode removeElements(ListNode head, int val) {
//删除值相同的头结点后,可能新的头结点也值相等,用循环解决
while (head != null && head.val == val) {
head = head.next;
}
// 已经为null,提前退出
if (head == null) {
return head;
}
// 已确定当前head.val != val
ListNode pre = head;
ListNode cur = head.next;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return head;
}
迭代
(虚拟节点)
- 添加一个虚拟头结点,删除头结点就不用另做考虑
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
// 因为删除可能涉及到头节点,所以设置dummy节点,统一操作
ListNode dummy = new ListNode(-1, head);
ListNode pre = dummy;
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}
递归
head
为空,此时直接返回head
- 当
head
不为空时,递归地进行删除操作 - 判断
head
的节点值是否等于val
并决定是否要删除head
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)
return null;
head.next=removeElements(head.next,val);
if(head.val==val){
return head.next;
}else{
return head;
}
}
}
边栏推荐
- Sklearn Feature Engineering (summary)
- socke.io長連接實現推送、版本控制、實時活躍用戶量統計
- mysql常用函数
- Slow content advertising: the long-term principle of brand growth
- High quality domestic stereo codec cjc8988, pin to pin replaces wm8988
- 使用SSM框架,配置多个数据库连接
- 深度學習19種損失函數
- Jenkins continuous integration 1
- Qtcanpool q05: no border
- 5G网络整体架构
猜你喜欢
CAD二次开发+NetTopologySuite+PGIS 引用多版本DLL问题
Openharmony gnawing paper growth plan -- json-rpc
Lombok @equalsandhashcode annotation how to make objects The equals () method compares only some attributes
Xcode13.3.1 项目执行pod install后报错
JSP
What are the advantages of e-mail marketing? Why do sellers of shopline independent station attach so much importance to it?
AutoCAD C# 多段线自相交检测
Xcode13.3.1 error reported after pod install
pytorch详解
Development trend of mobile advertising: Leveraging stock and fine marketing
随机推荐
MR-WordCount
YYGH-6-微信登录
5G网络整体架构
@Autowired注解为空的原因
YYGH-8-预约挂号
全球国家(和地区)信息JSON数据
The windows environment redis uses AOF persistence and cannot generate an AOF file. After generation, the content of the AOF file cannot be loaded
windows上安装redis并永久修改密码,及ssm框架集成redis
Caused by: com. fasterxml. jackson. databind. Exc.invalidformatexception: exception resolution
Academic search related papers
pytorch dataloader的长度 epoch与iteration的区别
MySQL common functions
CSI以及本地盘的相关实现记录
YYGH-BUG-03
Taobao seo training video course [22 lectures]
AutoCAD C# 多段线自相交检测
Idea generates entity classes from database tables
Qtcanpool q05: no border
Valueerror: iterative over raw text documents expected, string object received
Qtcanpool knowledge 07:ribbon