题目描述
给你一个链表的头节点 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
输出:[]
提示:
列表中的节点数目在范围 [0, 104] 内
1 <= Node.val <= 50
0 <= val <= 50
- 来源:力扣(LeetCode)
- 链接:https://leetcode.cn/problems/remove-linked-list-elements
核心:如何删除节点
如果把链表节点比作门牌号,链表中的next为其他房子的钥匙: 现有房子A,B,C, A有B的钥匙,B有C的钥匙. 当我们想要弃用B, 且能找得到C, 就需要把A中B的钥匙丢掉, 换成C的钥匙. 没有钥匙来开启B, B就被弃用了.
//删除cur节点
pre.next=cur.next;
//重置pre和cur的位置
pre=pre.next;
cur=pre.next;
初级解法: 迭代 – 头节点, 中间节点, 尾节点的分别判断
该解法 将整个列表看作三个对象, 并依次作判断与执行删除操作.
令current代表当前节点, 则当current的下一个节点不为空, 且current的下一个节点的值为val时, 对其进行删除
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
//Demo1
public ListNode removeElements(ListNode head, int val) {
//链表为空
if(head==null)
return null;
//判断头节点(两个特殊情况:链表中无元素/链表只有一个元素)
ListNode cur = head;
while(head.val==val){//头节点符合要求,删除头节点
head=head.next;
cur.next=null;
cur=head;
//头节点变化后重新判断链表情况
if(head==null){ //链表为空
return null;
}
if(head.next==null){ //只有一个节点
if(head.val==val)
return null;
else
return head;
}
}
//头节点不符合要求,判断剩下节点
if(cur.next==null)//说明链表只剩下一个不符合要求的元素
return head;
cur=cur.next;
ListNode pre = head;
while(cur.next!=null){
if(cur.val==val){
pre.next=cur.next;
cur=pre.next;
continue;
}
pre=pre.next;
cur=cur.next;
}
//如果最后一个节点值符合要求,把pre置空
if(cur.val==val){
pre.next=null;
}
return head;
}
}
进阶解法1: 迭代 – current与dummyHead
该解法使用一个虚拟头节点(dummyHead)巧妙地规避了繁杂的头节点判断, 把头节点当作中间节点之一.
设当前节点为current, 当前节点的下一个节点不为空持续循环, 并在其值等于val时进行删除; 在其值不为val时, current往前走一格
class Solution {
public ListNode removeElements(ListNode head, int val) {
//创建虚拟头节点dummyHead
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode current = dummyHead;
while(current.next!=null){
if(current.next.val==val){
current.next=current.next.next;
}else{
current=current.next;
}
}
return dummyHead.next;
}
}
进阶解法2: 递归
每次都递归都传入head.next, 这样在每次递归中, 我们都能够直接访问head节点(即当前节点)和head.next节点(下一个节点)
- 停止条件: head(当前节点)为null
- 如何删除: 仅返回值不为val的节点的地址(return head.val==val? head.next : head), 并将改节点地址赋给当前节点的next. 即: head.next = removeElements(head.next,val)
图片阅读顺序: 先从左到右只看蓝色, 再从右到左只看橘色
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
}