✅ [Python/C++/Java/Rust] slow & fast pointers (explained) + BONUS ONE-LINER
\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.\n*\nThis solution employs slow and fast pointers to keep track of middle and last nodes in the list. Time compl
**\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\nThis solution employs slow and fast pointers to keep track of middle and last nodes in the list. Time complexity is linear: **O(N)**. Space complexity is constant: **O(1)**.\n****\n\n**Comment.** The size of linked list is not known in advance, thus, we have to iterate till its end to count nodes. In the second pass, we iterate again and stop at the middle node. There is a convenient trick to enclose both iterations into a single loop, namely, using two pointers. First (slow) pointer would iterate with a regular speed (i.e., one node at a time) while the second (fast) pointer would be twice as fast. This means that when fast pointer hits the end of the list, the slow one will be precisely at the middle node.\n\n**Python #1.** Fast & slow pointers.\n```python\nclass Solution:\n    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        slow = fast = head\n        while fast and fast.next: \n            slow = slow.next\n            fast = fast.next.next\n        return slow\n```\n\n**Python #2.** Memory-inefficient, but concise.\n```python\nclass Solution:\n    def middleNode(self, h):\n        \n        def gen(n): \n            while (n:=n.next) : yield n\n        \n        nodes = [n for n in gen(ListNode(0,h))]\n\n        return nodes[len(nodes)//2]\n```\n\n<iframe src="https://leetcode.com/playground/8oh5SXVJ/shared" frameBorder="0" width="800" height="300"></iframe>\n\n**\u2705 YOU MADE IT TILL THE BONUS SECTION... YOUR GREAT EFFORT DESERVES UPVOTING THIS POST!**\n\n**Python.** Default arguments can not depend on other arguments, thus, we initialize recursion in a tricky way.\n```python\nclass Solution:\n    def middleNode(self, s, f="."):        \n        return (self.middleNode(s.next, f.next.next) if f and f.next else s) if f != "." else self.middleNode(s,s)\n```\n\n**C++.** Not a one-liner, but close to it.\n```cpp\nclass Solution \n{\npublic:\n    ListNode* middleNode(ListNode* h)\n    {\n        for (ListNode *f = h; f && f->next; h = h->next, f = f->next->next);\n        return h;\n    }\n};\n```
[]