mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Merge pull request #1008 from xiaofei-2020/ts5
添加(0019.删除链表的倒数第N个节点.md):增加typescript版本
This commit is contained in:
@ -181,7 +181,71 @@ var removeNthFromEnd = function(head, n) {
|
|||||||
return ret.next;
|
return ret.next;
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
TypeScript:
|
||||||
|
|
||||||
|
版本一(快慢指针法):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
|
||||||
|
let newHead: ListNode | null = new ListNode(0, head);
|
||||||
|
let slowNode: ListNode | null = newHead,
|
||||||
|
fastNode: ListNode | null = newHead;
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
fastNode = fastNode.next;
|
||||||
|
}
|
||||||
|
while (fastNode.next) {
|
||||||
|
fastNode = fastNode.next;
|
||||||
|
slowNode = slowNode.next;
|
||||||
|
}
|
||||||
|
slowNode.next = slowNode.next.next;
|
||||||
|
return newHead.next;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
版本二(计算节点总数法):
|
||||||
|
|
||||||
|
```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
|
||||||
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
|
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
|
||||||
val pre = ListNode(0).apply {
|
val pre = ListNode(0).apply {
|
||||||
|
Reference in New Issue
Block a user