-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution-check-input.ts
58 lines (45 loc) · 1023 Bytes
/
solution-check-input.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
56
57
58
/*
* @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 => {
// * ['52 ms', '95.38 %', '34 MB', '81.82 %']
if (head === null || n <= 0) return head;
const dummy = { next: head } as ListNode;
let ahead: MaybeList = dummy;
let behind: MaybeList = dummy;
let count = 0;
while (count < n) {
// * list shorter than n
if (ahead.next === null) return head;
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 };