Given the head
of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: head = [1,2,3,4,5]
Output:
[3,4,5]
Explanation:
The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6]
Output:
[4,5,6]
Explanation:
Since the list has two middle nodes with values 3 and 4, we return the second one.
Constraints:
- The number of nodes in the list is in the range
[1, 100]
. 1 <= Node.val <= 100
Result
Runtime: 110 ms, faster than 33.94% of TypeScript online submissions for Middle of the Linked List.
Memory Usage: 42.5 MB, less than 94.79% of TypeScript online submissions for Middle of the Linked List.
const middleNode = (head: ListNode | null): ListNode | null => {
let slow: ListNode | null = head, fast: ListNode | null = head
while (fast && fast.next) {
slow = slow.next
fast = fast.next.next
}
return slow
}
Result
Runtime: 36 ms, faster than 86.93% of Python3 online submissions for Middle of the Linked List.
Memory Usage: 13.8 MB, less than 55.04% of Python3 online submissions for Middle of the Linked List.
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slow
Result
Runtime: 6 ms, faster than 83.74% of PHP online submissions for Middle of the Linked List.
Memory Usage: 19.4 MB, less than 14.19% of PHP online submissions for Middle of the Linked List.
class Solution
{
/**
* @param ListNode|null $head
* @return ListNode|null
*/
function middleNode(?ListNode $head): ?ListNode
{
$slow = $fast = $head;
while ($fast && $fast->next) {
list($slow, $fast) = array($slow->next, $fast->next->next);
}
return $slow;
}
}