Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program To Get The Middle Element Of A Linked List In A Single Iteration
A linked list stores data in non-contiguous memory locations using nodes connected by pointers. Each node contains data and a link to the next node. Finding the middle element efficiently requires the two-pointer technique to avoid multiple iterations.
Brute Force Approach
The brute force method requires two passes through the linked list ?
First pass: Count total nodes to find length
Second pass: Traverse to the middle position (length/2)
Time complexity: O(n), but requires two iterations
Two-Pointer Technique (Single Iteration)
This optimal approach uses slow and fast pointers moving at different speeds ?
Slow pointer moves one step at a time
Fast pointer moves two steps at a time
When fast pointer reaches the end, slow pointer is at the middle
Algorithm
Initialize both slow and fast pointers to head
Move fast pointer two steps and slow pointer one step
Continue until fast pointer reaches end
Slow pointer now points to the middle element
Implementation
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, newVal):
newNode = Node(newVal)
newNode.next = self.head
self.head = newNode
def find_middle_element(self):
if self.head is None:
print("List is empty")
return None
slow = self.head
fast = self.head
while fast is not None and fast.next is not None:
slow = slow.next # Move one step
fast = fast.next.next # Move two steps
return slow.val
def display(self):
temp = self.head
if temp is None:
print("The list is empty")
return
print("Linked list elements:", end=" ")
while temp is not None:
print(temp.val, end=" ")
temp = temp.next
print()
# Create and test the linked list
linked_list = LinkedList()
for value in [5, 4, 3, 2, 1]:
linked_list.insert_at_beginning(value)
linked_list.display()
middle = linked_list.find_middle_element()
print(f"The middle element is: {middle}")
Linked list elements: 1 2 3 4 5 The middle element is: 3
Example with Even Number of Nodes
# Test with even number of nodes
linked_list2 = LinkedList()
for value in [6, 5, 4, 3, 2, 1]:
linked_list2.insert_at_beginning(value)
linked_list2.display()
middle2 = linked_list2.find_middle_element()
print(f"The middle element is: {middle2}")
Linked list elements: 1 2 3 4 5 6 The middle element is: 4
Key Points
Time Complexity: O(n) with single pass
Space Complexity: O(1) - only two pointers used
For even-length lists, returns the second middle element
Handles empty lists gracefully
Conclusion
The two-pointer technique efficiently finds the middle element in a single iteration. The slow pointer reaches the middle when the fast pointer completes the traversal, making this approach optimal for linked list problems.
