How to Find Middle of Linked List in C: Simple Method
To find the middle of a linked list in C, 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 (NULL), slow points to the middle node.
c
struct Node {
int data;
struct Node* next;
};
struct Node* findMiddle(struct Node* head) {
struct Node* slow = head;
struct Node* fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}Example
This example creates a linked list with 5 nodes and finds the middle node using the fast and slow pointer method.
c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* findMiddle(struct Node* head) {
struct Node* slow = head;
struct Node* fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int main() {
struct Node* head = createNode(10);
head->next = createNode(20);
head->next->next = createNode(30);
head->next->next->next = createNode(40);
head->next->next->next->next = createNode(50);
struct Node* middle = findMiddle(head);
if (middle != NULL) {
printf("Middle node data: %d\n", middle->data);
} else {
printf("List is empty\n");
}
return 0;
}Output
Middle node data: 30
Common Pitfalls
Common mistakes when finding the middle of a linked list include:
- Not checking if the list is empty (
head == NULL). - Incorrect loop condition causing
fastto accessNULLpointers. - Moving
fastpointer incorrectly (should move two steps, not one).
Always check fast != NULL && fast->next != NULL in the loop condition to avoid errors.
c
/* Wrong way: fast moves one step only, so slow won't reach middle correctly */ while (fast != NULL) { slow = slow->next; fast = fast->next; // moves one step only } /* Correct way: fast moves two steps */ while (fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; }
Quick Reference
- Use two pointers:
slowandfast. - Move
slowby one node,fastby two nodes. - Stop when
fastreaches end orfast->nextisNULL. slowwill point to the middle node.
Key Takeaways
Use two pointers moving at different speeds to find the middle efficiently.
Always check for NULL pointers to avoid runtime errors.
The slow pointer will point to the middle when the fast pointer reaches the end.
This method works for both even and odd length linked lists.
Initialize both pointers at the head of the list before starting the loop.