Skip to content

Commit 12a871a

Browse files
committed
https://leetcode.cn/problems/remove-nth-node-from-end-of-list
1 parent 4b15784 commit 12a871a

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,8 @@ https://leetcode.cn/problems/calculator-lcci
582582

583583
https://leetcode.cn/problems/longest-palindromic-substring
584584

585+
https://leetcode.cn/problems/remove-nth-node-from-end-of-list
586+
585587
#### 安装教程
586588

587589
1. 安装`deno`
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { ListNode } from "../reverse-linked-list/ListNode.ts";
2+
export default function removeNthFromEnd(
3+
head: ListNode | null,
4+
n: number,
5+
): ListNode | null {
6+
if (!head) return head;
7+
const nodes: ListNode[] = [];
8+
9+
let cur: ListNode | null = head;
10+
while (cur) {
11+
nodes.push(cur);
12+
cur = cur.next;
13+
}
14+
15+
if (nodes.length < n) {
16+
return null;
17+
}
18+
19+
if (nodes.length === n) {
20+
return nodes[1] || null;
21+
}
22+
if (nodes.length > n) {
23+
const pre = nodes[nodes.length - n - 1];
24+
const succ = nodes[nodes.length - n + 1];
25+
26+
if (pre) {
27+
pre.next = succ || null;
28+
}
29+
}
30+
return head;
31+
}

0 commit comments

Comments
 (0)