-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path876-middle-of-the-linked-list.js
More file actions
36 lines (34 loc) · 1012 Bytes
/
876-middle-of-the-linked-list.js
File metadata and controls
36 lines (34 loc) · 1012 Bytes
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
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var middleNode = function(head) {
// Determine how many nodes the linked list has
// If it has an odd number, choose the middle
// If it has an even number, choose the one to the right of the middle
// Brute force would be to traverse the entirety of the list and count the node
if (head === null) return null
let refHead = head
let count = 1
while (head.next) {
count++
head = head.next
};
let targetNodePosition = count % 2 === 0 ? Math.ceil(count / 2) : Math.ceil(count / 2) - 1
while (targetNodePosition > 0) {
refHead = refHead.next
targetNodePosition--
}
return refHead
};
/**
* Things to fix or think about further:
* Why do I need to subtract one in the odd case only?
*/