mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
添加(0019.删除链表的倒数第N个节点.md):typescript版本增加新解法
This commit is contained in:
@ -183,6 +183,8 @@ var removeNthFromEnd = function(head, n) {
|
|||||||
```
|
```
|
||||||
TypeScript:
|
TypeScript:
|
||||||
|
|
||||||
|
版本一(快慢指针法):
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
|
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
|
||||||
let newHead: ListNode | null = new ListNode(0, head);
|
let newHead: ListNode | null = new ListNode(0, head);
|
||||||
@ -200,6 +202,48 @@ function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
版本二(计算节点总数法):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
|
||||||
|
let curNode: ListNode | null = head;
|
||||||
|
let listSize: number = 0;
|
||||||
|
while (curNode) {
|
||||||
|
curNode = curNode.next;
|
||||||
|
listSize++;
|
||||||
|
}
|
||||||
|
if (listSize === n) {
|
||||||
|
head = head.next;
|
||||||
|
} else {
|
||||||
|
curNode = head;
|
||||||
|
for (let i = 0; i < listSize - n - 1; i++) {
|
||||||
|
curNode = curNode.next;
|
||||||
|
}
|
||||||
|
curNode.next = curNode.next.next;
|
||||||
|
}
|
||||||
|
return head;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
版本三(递归倒退n法):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
|
||||||
|
let newHead: ListNode | null = new ListNode(0, head);
|
||||||
|
let cnt = 0;
|
||||||
|
function recur(node) {
|
||||||
|
if (node === null) return;
|
||||||
|
recur(node.next);
|
||||||
|
cnt++;
|
||||||
|
if (cnt === n + 1) {
|
||||||
|
node.next = node.next.next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
recur(newHead);
|
||||||
|
return newHead.next;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
Kotlin:
|
Kotlin:
|
||||||
|
|
||||||
```Kotlin
|
```Kotlin
|
||||||
|
Reference in New Issue
Block a user