How to Find Middle of Linked List in Python Easily
To find the middle of a linked list in Python, use two pointers:
slow moves one step at a time, and fast moves two steps. When fast reaches the end, slow will be at the middle node.Syntax
Use two pointers to traverse the linked list:
- slow: moves one node at a time
- fast: moves two nodes at a time
When fast reaches the end, slow points to the middle.
python
slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next # slow now points to the middle node
Example
This example creates a linked list and finds its middle node using the two-pointer method.
python
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node def find_middle(self): slow = self.head fast = self.head while fast and fast.next: slow = slow.next fast = fast.next.next return slow.data if slow else None # Create linked list and add elements ll = LinkedList() for value in [10, 20, 30, 40, 50]: ll.append(value) # Find and print middle print(ll.find_middle())
Output
30
Common Pitfalls
Common mistakes include:
- Not checking if the list is empty before starting.
- Advancing
fastpointer without checking iffast.nextexists, causing errors. - Returning the wrong node when the list has even length (this method returns the second middle node).
Always check pointers before moving them to avoid crashes.
python
def find_middle_wrong(head): slow = head fast = head while fast and fast.next and fast.next.next: # Fixed: check fast is not None slow = slow.next fast = fast.next.next return slow.data if slow else None # Correct way def find_middle_correct(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow.data if slow else None
Quick Reference
- Use two pointers:
slowandfast. - Move
slowby one step,fastby two steps. - When
fastreaches the end,slowis at the middle. - Check for empty list before processing.
- For even length lists, this method returns the second middle node.
Key Takeaways
Use two pointers moving at different speeds to find the middle efficiently.
Always check if pointers are valid before moving to avoid errors.
This method works in one pass with O(n) time and O(1) space.
For even-length lists, the method returns the second middle node by default.
Handle empty linked lists gracefully to prevent crashes.