简单给你一个链表的头节点 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
输出:[]
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/linked-list/f9izv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
代码
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function (head, val) {
if (head === null) {
return null;
}
let fast = head.next;
let slow = head;
if (fast === null) {
if (slow.val === val) {
return null;
}
return slow;
}
while (fast !== null) {
if (fast.val === val) {
slow.next = slow.next.next;
} else if (slow.val === val) {
slow = fast;
fast = fast.next;
head = slow;
continue;
} else {
slow = slow.next;
}
fast = fast.next;
}
if (slow.next === null && slow.val === val) {
return null;
}
return head;
};
思路:快慢指针(双指针)
- 首先排除特殊情况和。即head为null,此时直接返回null即可;
接下来设置快慢指针:
let slow = head;
let fast = head.next; // slow.next
此时第2个特殊情况出现了:即链表长度为1的情况。所以我们需要提前处理
//链表长度为1显然fast为null
if (fast === null) {
if (slow.val === val) {
// 当slow.val===val,唯一的节点也被删除了,所以只能返回null
return null;
}
// 倘若slow.val!==val,直接返回slow即可
return slow;
}
进入遍历,需要处理两种情况:1.慢指针slow.val===val; 2.快指针fast.val===val。
while (fast !== null) {
if (fast.val === val) {
slow.next = slow.next.next;
} else if (slow.val === val) {
// 若慢指针slow.val===val,下面的操作就可以提前跳过了
slow = fast;
fast = fast.next;//slow.next
head = slow;//重置头节点:因为这种情况下slow肯定是当前链表的头节点!不然fast肯定会先遇到fast.val===val的情况
continue;
} else {
slow = slow.next;
}
fast = fast.next;
}