-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path29-2095.ts
41 lines (33 loc) · 927 Bytes
/
29-2095.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
// https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/description/?envType=study-plan-v2&envId=leetcode-75
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
// @ts-nocheck
const deleteMiddle = (head: ListNode | null): ListNode | null => {
let tempHead = head,
size = 0;
while (tempHead) {
tempHead = tempHead.next;
size++;
}
const middleNodeIdx = Math.floor(size / 2);
if (middleNodeIdx === 0) return head?.next ?? null;
let i = 1,
prev = head,
curr = head?.next ?? null;
while (i !== middleNodeIdx && curr) {
prev = curr;
curr = curr?.next ?? null;
i++;
}
prev.next = curr?.next ?? null;
return head;
};