Skip to content

Commit 773f170

Browse files
committed
Add week 12 solutions: remove-nth-node-from-end-of-list
1 parent c4535e6 commit 773f170

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* https://leetcode.com/problems/remove-nth-node-from-end-of-list/
3+
* time complexity : O(n)
4+
* space complexity : O(1)
5+
*/
6+
7+
class ListNode {
8+
val: number
9+
next: ListNode | null
10+
constructor(val?: number, next?: ListNode | null) {
11+
this.val = (val === undefined ? 0 : val)
12+
this.next = (next === undefined ? null : next)
13+
}
14+
}
15+
16+
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
17+
const dummy = new ListNode(0, head);
18+
let first: ListNode | null = dummy;
19+
let second: ListNode | null = dummy;
20+
21+
for (let i = 0; i <= n; i++) {
22+
if (first !== null) first = first.next;
23+
}
24+
25+
while (first !== null) {
26+
first = first.next;
27+
second = second!.next;
28+
}
29+
30+
if (second !== null && second.next !== null) second.next = second.next.next;
31+
32+
return dummy.next;
33+
};

0 commit comments

Comments
 (0)