How can you find the middle element of a linked list in two passes?

Arrays Linked Lists Questions Medium



46 Short 80 Medium 67 Long Answer Questions Question Index

How can you find the middle element of a linked list in two passes?

To find the middle element of a linked list in two passes, you can follow the below steps:

1. Initialize two pointers, slow and fast, pointing to the head of the linked list.
2. In the first pass, move the fast pointer two nodes ahead and the slow pointer one node ahead at each iteration.
3. Continue this process until the fast pointer reaches the end of the linked list. By the time the fast pointer reaches the end, the slow pointer will be pointing to the middle element of the linked list.
4. In the second pass, return the value of the node pointed by the slow pointer as the middle element.

Here is the implementation in Python:


```python
def find_middle_element(head):
slow = head
fast = head

while fast and fast.next:
slow = slow.next
fast = fast.next.next

return slow.value
```

In this approach, the fast pointer moves twice as fast as the slow pointer, so when the fast pointer reaches the end of the linked list, the slow pointer will be at the middle element. This solution requires two passes through the linked list.