-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.ts
42 lines (37 loc) · 1001 Bytes
/
res.ts
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
/**
* 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)
* }
* }
*/
/**
* 递归迭代均可,此法为迭代
* @param head
* @param val
*/
function removeElements(head: ListNode | null, val: number): ListNode | null {
let result = head;
let prevPointer = null;
let currentPointer = head;
if (!currentPointer) {
return result?.val === val ? null : head;
}
while (currentPointer) {
if (currentPointer.val === val) {
if (prevPointer) {
prevPointer.next = currentPointer.next;
} else {
result = currentPointer.next;
}
} else {
prevPointer = currentPointer;
}
currentPointer = currentPointer.next;
}
return result;
};