3217. Delete Nodes From Linked List Present in Array
题目简介
/**
* @param {number[]} nums
* @param {ListNode} head
* @return {ListNode}
*/
这是一道关于链表的题目,题目首先给我们一个链表头 head 以及一个数组 nums
题目要求我们遍历整个链表,删除链表元素的值在 nums 数组中出现的链表元素
最后返回修改后的链表的头
解题思路
这道题如果我们从 head 出发,会发现情况有两种:
- head 指向的元素的只在 nums 中存在
- 反之,不存在
这两种的情况我们需要分开处理,会让逻辑分散
这种情况我们通常需要引入一个 “假” 的链表头来辅助我们,姑且称之为 dummy,它也是该链表的一个元素,只不过它的 next 指针指向 head
现在我们从 dummy 的视角来看这个题目,两种情况及其解决方案:
- head(也就是
dummy.next)元素的值存在与 nums 中:我们只需要把dummy.next = dummy.next.next即可 - 反之,不存在:我们正常遍历链表下一个元素即可
为了方便遍历,我们用一个指针 cur 来指向 dummy,遍历结束条件为 cur.next === null(也就是当前 cur 指向了链表最后一个元素)
Javascript
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {number[]} nums
* @param {ListNode} head
* @return {ListNode}
*/
var modifiedList = function(nums, head) {
const set = new Set(nums)
const dummy = new ListNode(0, head)
let cur = dummy
while(cur.next) {
if(set.has(cur.next.val)) {
cur.next = cur.next.next
} else {
cur = cur.next
}
}
return dummy.next
};