Skip to content

Commit f190780

Browse files
committed
✨ [19] Remove Nth Node From End of List
still very confused
1 parent 1982557 commit f190780

File tree

3 files changed

+64
-1
lines changed

3 files changed

+64
-1
lines changed

19/my_solution.js

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
class ListNode {
9+
constructor(val, next) {
10+
this.val = (val === undefined ? 0 : val);
11+
this.next = (next === undefined ? null : next);
12+
}
13+
}
14+
15+
const removeNthFromEnd = (head, n) => {
16+
// l = slow, r = fast
17+
let dummy = new ListNode(0, head),
18+
l = dummy,
19+
r = head;
20+
21+
while (n > 0) {
22+
r = r.next;
23+
n--;
24+
}
25+
26+
while (null !== r) {
27+
l = l.next;
28+
r = r.next;
29+
}
30+
31+
// QUESITON: I dont understand this part
32+
// Delete the node
33+
l.next = l.next.next;
34+
35+
return dummy.next;
36+
}
37+
38+
let x = new ListNode(0, new ListNode(2, new ListNode(4))),
39+
y = x;
40+
console.log(y)
41+
42+
x.next.next = null;
43+
console.log(x)

19/solution.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const removeNthFromEnd = (head, n) => {
2+
let dummy = new ListNode(0, head),
3+
l = dummy,
4+
r = head;
5+
6+
while (n > 0) {
7+
r = r.next;
8+
n--;
9+
}
10+
11+
while (null !== r) {
12+
l = l.next;
13+
r = r.next;
14+
}
15+
16+
l.next = l.next.next;
17+
18+
return dummy.next;
19+
}

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
- [7. Generate Parentheses](./7/)
1717
- [11. Container With Most Water](./11/)
1818
- [15. 3Sum](./15/)
19+
- [19. Remove Nth Node From End of List](./19/)
1920
- [21. Merge Two Sorted Lists](./21/)
2021
- [22. Generate Parentheses](./22/)
2122
- [23. Merge k Sorted Lists](./23/)
@@ -65,7 +66,7 @@ iex ./.../solution.ex
6566

6667
Batch create in bash
6768
```ssh
68-
chapter=141 && mkdir ./$chapter && touch ./$chapter/my_solution.js && touch ./$chapter/solution.js && alias x="node ./$chapter/my_solution.js"
69+
chapter=19 && mkdir ./$chapter && touch ./$chapter/my_solution.js && touch ./$chapter/solution.js && alias x="node ./$chapter/my_solution.js"
6970
```
7071
> And now you can use `x` for quick debug.
7172

0 commit comments

Comments
 (0)