-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMidpoint.js
More file actions
26 lines (25 loc) · 735 Bytes
/
Midpoint.js
File metadata and controls
26 lines (25 loc) · 735 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
// --- Directions
// Return the 'middle' node of a linked list.
// If the list has an even number of elements, return
// the node at the end of the first half of the list.
// *Do not* use a counter variable, *do not* retrieve
// the size of the list, and only iterate
// through the list one time.
// --- Example
// const l = new LinkedList();
// l.insertLast('a')
// l.insertLast('b')
// l.insertLast('c')
// midpoint(l); // returns { data: 'b' }
function midpoint(list) {
if (!list.head){
return null;
}
let slow = list.head;
let fast = list.head;
while(fast.next && fast.next.next){
slow = slow.next
fast = fast.next.next
}
return slow
}