Skip to content

Commit e808b1a

Browse files
committed
Feat: 19. Remove Nth Node From End of List
1 parent 04c02d7 commit e808b1a

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+
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+
/**
11+
* https://leetcode.com/problems/remove-nth-node-from-end-of-list
12+
* T.C. O(N)
13+
* S.C. O(1)
14+
*/
15+
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
16+
let first = head;
17+
let second = head;
18+
19+
for (let i = 0; i < n; i++)
20+
first = first!.next;
21+
22+
if (!first)
23+
return head!.next;
24+
25+
while (first.next) {
26+
first = first.next;
27+
second = second!.next;
28+
}
29+
30+
second!.next = second!.next!.next;
31+
32+
return head;
33+
}

0 commit comments

Comments
 (0)