1
+ /*
2
+ Given the head of a singly linked list, return the middle node of the linked list.
3
+
4
+ If there are two middle nodes, return the second middle node.
5
+
6
+ Example 1:
7
+
8
+ Input: head = [1,2,3,4,5]
9
+ Output: [3,4,5]
10
+ Explanation: The middle node of the list is node 3.
11
+
12
+ Example 2:
13
+
14
+ Input: head = [1,2,3,4,5,6]
15
+ Output: [4,5,6]
16
+ Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
17
+
18
+ Constraints:
19
+
20
+ The number of nodes in the list is in the range [1, 100].
21
+ 1 <= Node.val <= 100
22
+ */
23
+
24
+ /**
25
+ * Definition for singly-linked list.
26
+ * function ListNode(val, next) {
27
+ * this.val = (val===undefined ? 0 : val)
28
+ * this.next = (next===undefined ? null : next)
29
+ * }
30
+ */
31
+ /**
32
+ * @param {ListNode } head
33
+ * @return {ListNode }
34
+ */
35
+ var middleNode = function ( head ) {
36
+ let curr = head // Initialize the current node to the head
37
+ let size = 0 // Initialize the size to 0
38
+
39
+ // Traverse the Linked List
40
+ while ( curr ) {
41
+ size += 1 // Keep track of the size of the Linked List
42
+ curr = curr . next
43
+ } // curr is equal to null at the end of the loop
44
+
45
+ let mid = Math . floor ( size / 2 ) + 1 // Calculate the middle of the List
46
+ let count = 0
47
+ curr = head // Reset current to head
48
+
49
+ // Traverse the Linked List
50
+ while ( curr ) {
51
+ count += 1 // Keep track of the number of visited nodes in the List
52
+
53
+ if ( count === mid ) return curr // When middle node found, return it
54
+
55
+ curr = curr . next
56
+ }
57
+ } ;
0 commit comments