Skip to content

Commit df9f1ed

Browse files
committed
remove nth node from end of list solution
1 parent 07f122a commit df9f1ed

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number
5+
* next: ListNode | null
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
* }
11+
*/
12+
13+
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
14+
if (!head) return null;
15+
16+
let current = head;
17+
let nodeLen = 0;
18+
while (current.next) {
19+
current = current.next;
20+
nodeLen++;
21+
}
22+
23+
if (nodeLen - n < 0) return head.next;
24+
25+
current = head;
26+
let count = 0;
27+
while (count < nodeLen - n) {
28+
current = current.next;
29+
count++;
30+
}
31+
current.next = current.next.next;
32+
33+
return head;
34+
}

0 commit comments

Comments
 (0)