-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.ts
55 lines (43 loc) · 944 Bytes
/
solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
* @lc app=leetcode id=19 lang=javascript
*
* [19] Remove Nth Node From End of List
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
type MaybeList = ListNode | null;
interface ListNode {
val: number;
next: MaybeList;
}
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
const removeNthFromEnd = (head: MaybeList, n: number): MaybeList => {
// * ['48 ms', '98.59 %', '34.1 MB', '68.18 %']
if (head === null) return head;
const dummy = { next: head } as ListNode;
let ahead: MaybeList = dummy;
let behind: MaybeList = dummy;
let count = 0;
while (count < n) {
ahead = ahead.next!;
count++;
}
while (ahead.next) {
ahead = ahead.next;
behind = behind.next!;
}
behind.next = behind.next!.next;
return dummy.next;
};
// @lc code=end
export { removeNthFromEnd };