/*
* @lc app=leetcode.cn id=203 lang=typescript
*
* [203] 移除链表元素(虚拟头结点迭代,避免处理头结点时需要不同操作)
*/
// @lc code=start
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function removeElements(head: ListNode | null, val: number): ListNode | null {
//虚拟头结点
const data = new ListNode(0, head);
let cur = data.next,
pre = data;
while (cur) {
if (cur.val === val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
//注意返回时要去掉虚拟头结点
return data.next;
}
// @lc code=end