Skip to content

Commit 7458c5b

Browse files
committed
https://leetcode.cn/problems/print-immutable-linked-list-in-reverse/
1 parent 37e1db1 commit 7458c5b

File tree

4 files changed

+58
-0
lines changed

4 files changed

+58
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ leetcode 测试
1010

1111
##### 包含的内容如下
1212

13+
https://leetcode.cn/problems/print-immutable-linked-list-in-reverse/
14+
1315
https://leetcode.cn/problems/plus-one-linked-list/
1416

1517
https://leetcode.cn/problems/minimum-swaps-to-make-sequences-increasing/
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
export class ImmutableListNode {
2+
#print;
3+
#index = 0;
4+
#array: number[];
5+
constructor(array: Array<number>, print: (value: number) => void) {
6+
if (array.length === 0) throw Error("input empty array");
7+
this.#print = print;
8+
this.#array = array;
9+
}
10+
printValue() {
11+
this.#print(this.#array[this.#index]);
12+
}
13+
getNext(): ImmutableListNode | null {
14+
if (this.#index+1 >= this.#array.length) return null;
15+
const next = new ImmutableListNode(this.#array, this.#print);
16+
next.#index = this.#index + 1;
17+
return next;
18+
}
19+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { ImmutableListNode } from "./ImmutableListNode.ts";
2+
3+
export default function printLinkedListInReverse(
4+
head: ImmutableListNode | null
5+
) {
6+
if (head !== null) {
7+
printLinkedListInReverse(head.getNext());
8+
head.printValue();
9+
}
10+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { ImmutableListNode } from "./ImmutableListNode.ts";
2+
import printLinkedListInReverse from "./index.ts";
3+
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
4+
5+
Deno.test("print-immutable-linked-list-in-reverse", () => {
6+
const cases = [
7+
[
8+
[1, 2, 3, 4],
9+
[4, 3, 2, 1],
10+
],
11+
[
12+
[0, -4, -1, 3, -5],
13+
[-5, 3, -1, -4, 0],
14+
],
15+
[
16+
[-2, 0, 6, 4, 4, -6],
17+
[-6, 4, 4, 6, 0, -2],
18+
],
19+
];
20+
cases.forEach(([input, output]) => {
21+
const result: number[] = [];
22+
const node = new ImmutableListNode(input, (v) => result.push(v));
23+
printLinkedListInReverse(node);
24+
25+
assertEquals(output, result);
26+
});
27+
});

0 commit comments

Comments
 (0)