203.remove-linked-list-elements.md 2.0 KB
Newer Older
L
luzhipeng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
## 题目地址
https://leetcode.com/problems/remove-linked-list-elements/description/

## 题目描述
```
Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

```

## 思路
这个一个链表基本操作的题目,思路就不多说了。
## 关键点解析

- 链表的基本操作(删除指定节点)
- 虚拟节点dummy 简化操作

> 其实设置dummy节点就是为了处理特殊位置(头节点),这这道题就是如果头节点是给定的需要删除的节点呢?
为了保证代码逻辑的一致性,即不需要为头节点特殊定制逻辑,才采用的虚拟节点。

- 如果连续两个节点都是要删除的节点,这个情况容易被忽略。
eg:

```js
// 只有下个节点不是要删除的节点才更新current
if (!next || next.val !== val) {
    current =  next;
}

```


## 代码

```js



/*
 * @lc app=leetcode id=203 lang=javascript
 *
 * [203] Remove Linked List Elements
 *
 * https://leetcode.com/problems/remove-linked-list-elements/description/
 *
 * algorithms
 * Easy (35.32%)
 * Total Accepted:    211.9K
 * Total Submissions: 598.6K
 * Testcase Example:  '[1,2,6,3,4,5,6]\n6'
 *
 * Remove all elements from a linked list of integers that have value val.
 * 
 * Example:
 * 
 * 
 * Input:  1->2->6->3->4->5->6, val = 6
 * Output: 1->2->3->4->5
 * 
 * 
 */
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
var removeElements = function(head, val) {
    const dummy = {
        next: head
    }
    let current = dummy;

    while(current && current.next) {
        let next = current.next;
        if (next.val === val) {
            current.next = next.next;
            next = next.next;
        }

        if (!next || next.val !== val) {
            current =  next;
        }
    }

    return dummy.next;
};

```