876. Middle of the Linked List
Asked at 12Amazon52Google49Microsoft47Meta43Apple43Bloomberg42IBM50Walmart Labs82AMD69Accenture54tcs50Nvidia39
Problem
Return the middle node of a linked list; when there are two middle nodes, return the second.
Example: 1→2→3→4→5 → node 3; 1→2→3→4→5→6 → node 4
Fast moves two steps, slow one; when fast runs out, slow is at the middle (the second middle for even lengths).
Complexity: O(n) time, O(1) space.
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
assert Solution().middleNode(make_list([1, 2, 3, 4, 5])).val == 3
assert Solution().middleNode(make_list([1, 2, 3, 4, 5, 6])).val == 4
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; }
return slow;
}
}
func middleNode(head *ListNode) *ListNode {
slow, fast := head, head
for fast != nil && fast.Next != nil {
slow, fast = slow.Next, fast.Next.Next
}
return slow
}