Skip to content

Commit e32220b

Browse files
Jeehay28Jeehay28
authored andcommitted
Add remove-nth-node-from-end-of-list solution in TS
1 parent 5d48199 commit e32220b

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class ListNode {
2+
val: number;
3+
next: ListNode | null;
4+
constructor(val?: number, next?: ListNode | null) {
5+
this.val = val === undefined ? 0 : val;
6+
this.next = next === undefined ? null : next;
7+
}
8+
}
9+
10+
// TC: O(n)
11+
// SC: O(1)
12+
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
13+
let dummy = new ListNode();
14+
dummy.next = head;
15+
let fast: ListNode | null = dummy;
16+
let slow: ListNode | null = dummy;
17+
18+
for (let i = 0; i < n + 1; i++) {
19+
if (fast) {
20+
fast = fast.next;
21+
}
22+
}
23+
24+
while (fast) {
25+
fast = fast.next;
26+
slow = slow!.next;
27+
}
28+
29+
if (slow && slow.next) {
30+
slow.next = slow.next.next;
31+
}
32+
33+
return dummy.next;
34+
}
35+
36+
37+
// TC: O(n)
38+
// SC: O(n)
39+
// function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
40+
// let dummy = head;
41+
// const nodes: (ListNode | null)[] = [];
42+
43+
// while (dummy) {
44+
// nodes.push(dummy);
45+
// dummy = dummy.next;
46+
// }
47+
48+
// // first node: nodes.length === n
49+
// // last node: n === 1
50+
51+
// if (nodes.length === n) {
52+
// head = head!.next;
53+
// } else if (nodes.length > 1 && n === 1) {
54+
// nodes[nodes.length - 2]!.next = null;
55+
// } else {
56+
// nodes[nodes.length - n - 1]!.next = nodes[nodes.length - n + 1];
57+
// }
58+
59+
// return head;
60+
// }

0 commit comments

Comments
 (0)