Skip to content

添加 0203移除链表元素 JavaScript 版本 #2949

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions problems/0203.移除链表元素.md
Original file line number Diff line number Diff line change
Expand Up @@ -452,26 +452,56 @@ func removeElements(head *ListNode, val int) *ListNode {

### JavaScript:

使用虚拟头节点:

```js
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function(head, val) {
// 这样可以避免头节点就是目标值的情况需要特殊处理
const ret = new ListNode(0, head);
let cur = ret;
while(cur.next) {
if(cur.next.val === val) {
cur.next = cur.next.next;
while (cur.next) {
// 如果下一个节点的值等于目标值 val,跳过该节点
if (cur.next.val === val) {
cur.next = cur.next.next;
continue;
}
cur = cur.next;
}
// 返回虚拟头节点的下一个节点,即真正的链表头
return ret.next;
};
```

在原链表上删除:

```js
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function(head, val) {
// 先处理头部连续为 val 的节点
while (head && head.val === val) {
head = head.next;
}
let cur = head;
while (cur && cur.next) {
if (cur.next.val === val) {
cur.next = cur.next.next; // 跳过当前节点
} else {
cur = cur.next;
}
}
return head;
};
```

### TypeScript:

版本一(在原链表上直接删除):
Expand Down