class Node: def __init__(self, data): self.data = data self.next = None def find_middle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow.data # Linked list: 10 -> 20 -> 30 -> 40 -> 50 -> None head = Node(10) head.next = Node(20) head.next.next = Node(30) head.next.next.next = Node(40) head.next.next.next.next = Node(50) print(find_middle(head))
The slow pointer moves one step at a time, the fast pointer moves two steps. When fast reaches the end, slow is at the middle.
For the list 10 -> 20 -> 30 -> 40 -> 50, the middle is 30.
class Node: def __init__(self, data): self.data = data self.next = None def find_middle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow.data # Linked list: 1 -> 2 -> 3 -> 4 -> None head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) print(find_middle(head))
For even length lists, the slow pointer ends at the second middle node.
Here, the middle nodes are 2 and 3, so output is 3.
class Node: def __init__(self, data): self.data = data self.next = None def find_middle(head): slow = head fast = head while fast.next and fast.next.next: slow = slow.next fast = fast.next.next return slow.data head = None print(find_middle(head))
The condition 'while fast.next and fast.next.next' fails when fast is None, causing AttributeError when accessing fast.next.
The two-pointer method finds the middle in one pass by moving one pointer twice as fast as the other.
This avoids counting or extra memory.
class Node: def __init__(self, data): self.data = data self.next = None def find_middle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow.data head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) # Remove the third node (data=3) head.next.next = head.next.next.next print(find_middle(head))
After removing node with data 3, the list is 1 -> 2 -> 4 -> 5.
The middle nodes are 2 and 4, so the function returns the second middle, 4.
