Skip to content

Commit 14958f6

Browse files
committed
Remove Nth Node from the end of a linked list solution
1 parent a627c1d commit 14958f6

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

18-removeNthNodeFromEndOfList.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @param {number} n
11+
* @return {ListNode}
12+
*/
13+
var removeNthFromEnd = function (head, n) {
14+
let traverseList = (head) => {
15+
if (head === null) {
16+
return [];
17+
}
18+
19+
return [head].concat(traverseList(head.next));
20+
};
21+
22+
let arr = traverseList(head);
23+
let deleteIndex = arr.length - n;
24+
if (deleteIndex === 0) {
25+
return arr[1];
26+
} else if (deleteIndex > 0) {
27+
let prev = arr[deleteIndex - 1];
28+
prev.next = arr[deleteIndex + 1];
29+
return arr[0];
30+
} else {
31+
return [];
32+
}
33+
};
34+
let c = new ListNode(1);
35+
let b = new ListNode(45, c);
36+
let a = new ListNode(3, b);
37+
38+
let traverseList = (head) => {
39+
if (head === null) {
40+
return [];
41+
}
42+
43+
return [head].concat(traverseList(head.next));
44+
};
45+
46+
function ListNode(val, next) {
47+
this.val = val === undefined ? 0 : val;
48+
this.next = next === undefined ? null : next;
49+
}
50+
51+
let arr = traverseList(a);
52+
53+
console.log(arr[arr.length - 2]);

0 commit comments

Comments
 (0)