1
+ /*
2
+ Return the 'middle' node of a linked list.
3
+ If the list has an even number of elements, return the node at the end of the first half of the list.
4
+
5
+ *Do not* use a counter variable, *do not* retrive the size of the list, and only iterate through the list one time.
6
+
7
+ --Example
8
+
9
+ const l = new LinkedList();
10
+ l.insertLast('a');
11
+ l.insertLast('b');
12
+ l.insertLast('c');
13
+
14
+ midPoint(l); // returns { data: 'b' };
15
+ */
16
+
17
+ // -----------------------------------------------
18
+
19
+ const oddArr = [ 4 , 7 , 5 , 9 , 2 , 47 , 11 ] ; // 9
20
+ const evenArr = [ 4 , 7 , 5 , 9 , 2 , 47 ] // 5
21
+
22
+ function midPoint ( arr ) {
23
+ let slow = 0 ;
24
+ let fast = 0 ;
25
+
26
+ while ( arr [ fast + 2 ] ) {
27
+ slow += 1 ;
28
+ fast += 2 ;
29
+ }
30
+
31
+ return arr [ slow ] ;
32
+ }
33
+
34
+ console . log ( midPoint ( oddArr ) ) ; // 9
35
+ console . log ( midPoint ( evenArr ) ) ; // 5
36
+
37
+ // -----------------------------------------------
38
+
39
+ // Solution technique:
40
+ // We will use 2 pointer variables 'slow' and 'fast'.
41
+ // With each iteration slow will move ahead by 1 and fast will move ahead by 2.
42
+ // 'fast' will move twice as fast as 'slow'.
43
+ // So, when 'fast' will point to the last node, 'slow' must be pointing to the middle node.
0 commit comments