classSolution {
public ListNode middleNode(ListNode head) {
// Step 1: Calculate the length of the listint length = 0;
ListNode current = head;
while (current !=null) {
length++;
current = current.next;
}
// Step 2: Find the middle node's positionint mid = length / 2;
// Step 3: Traverse to the middle node current = head;
for (int i = 0; i < mid; i++) {
current = current.next;
}
return current;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defmiddleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Step 1: Calculate the length of the list length =0 current = head
while current:
length +=1 current = current.next
# Step 2: Find the middle node's position mid = length //2# Step 3: Traverse to the middle node current = head
for _ in range(mid):
current = current.next
return current
⏰ Time complexity: O(n), where n is length of linked list.
🧺 Space complexity: O(1)
Method 2 - Uses One Slow Pointer and One Fast Pointer 🏆#
Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list. This is done in single pass.
classSolution {
public ListNode middleNode(ListNode head) {
ListNode fast = head, slow = head;
while (fast !=null&& fast.next!=null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}
1
2
3
4
5
6
7
classSolution:
defmiddleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list.