mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
@ -302,7 +302,63 @@ var removeElements = function(head, val) {
|
||||
};
|
||||
```
|
||||
|
||||
TypeScript:
|
||||
|
||||
版本一(在原链表上直接删除):
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* 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 {
|
||||
// 删除头部节点
|
||||
while (head !== null && head.val === val) {
|
||||
head = head.next;
|
||||
}
|
||||
if (head === null) return head;
|
||||
let pre: ListNode = head, cur: ListNode = head.next;
|
||||
// 删除非头部节点
|
||||
while (cur) {
|
||||
if (cur.val === val) {
|
||||
pre.next = cur.next;
|
||||
} else {
|
||||
pre = pre.next;
|
||||
}
|
||||
cur = cur.next;
|
||||
}
|
||||
return head;
|
||||
};
|
||||
```
|
||||
|
||||
版本二(虚拟头节点):
|
||||
|
||||
```typescript
|
||||
function removeElements(head: ListNode | null, val: number): ListNode | null {
|
||||
head = new ListNode(0, head);
|
||||
let pre: ListNode = head, cur: ListNode = head.next;
|
||||
// 删除非头部节点
|
||||
while (cur) {
|
||||
if (cur.val === val) {
|
||||
pre.next = cur.next;
|
||||
} else {
|
||||
pre = pre.next;
|
||||
}
|
||||
cur = cur.next;
|
||||
}
|
||||
return head.next;
|
||||
};
|
||||
```
|
||||
|
||||
Swift:
|
||||
|
||||
```swift
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
|
@ -168,6 +168,32 @@ public class ListNode {
|
||||
}
|
||||
```
|
||||
|
||||
JavaScript:
|
||||
|
||||
```javascript
|
||||
class ListNode {
|
||||
val;
|
||||
next = null;
|
||||
constructor(value) {
|
||||
this.val = value;
|
||||
this.next = null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
TypeScript:
|
||||
|
||||
```typescript
|
||||
class ListNode {
|
||||
public val: number;
|
||||
public next: ListNode = null;
|
||||
constructor(value: number) {
|
||||
this.val = value;
|
||||
this.next = null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user