Skip to content

Commit 9ae0b36

Browse files
committed
sovle: remove nth node from end of list
1 parent e521fd6 commit 9ae0b36

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* TC: O(N)
3+
* SC: O(1)
4+
* N: list length
5+
*/
6+
7+
/**
8+
* Definition for singly-linked list.
9+
* function ListNode(val, next) {
10+
* this.val = (val===undefined ? 0 : val)
11+
* this.next = (next===undefined ? null : next)
12+
* }
13+
*/
14+
/**
15+
* @param {ListNode} head
16+
* @param {number} n
17+
* @return {ListNode}
18+
*/
19+
var removeNthFromEnd = function (head, n) {
20+
let listLength = 0;
21+
let pointer = head;
22+
23+
while (pointer) {
24+
pointer = pointer.next;
25+
listLength += 1;
26+
}
27+
28+
// if target of removal is the first node in list
29+
if (listLength === n) {
30+
return head.next;
31+
}
32+
33+
let nextCount = listLength - n - 1;
34+
pointer = head;
35+
36+
while (nextCount) {
37+
pointer = pointer.next;
38+
nextCount -= 1;
39+
}
40+
41+
pointer.next = pointer.next.next;
42+
43+
return head;
44+
};

0 commit comments

Comments
 (0)