Find the middle of a given linked list in C
Problem Statement: Given a Singly Linked list find the middle.
In the following approach, two pointers are maintained slow and fast. When the fast pointer reaches the end, the slow pointer reaches the middle position.
/*C code to find Middle of a Linked List */ #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; } NODE; NODE *head = NULL; NODE *newNode(int key) { NODE *temp = (NODE *)malloc(sizeof(NODE)); temp->data = key; temp->next = NULL; return temp; } int middle(NODE *head) { NODE *temp = head; NODE *slow = head; NODE *fast = head; if (temp != NULL) { while (fast != NULL && fast->next != NULL) { fast = fast->next->next; slow = slow->next; } return slow->data; } } void printList() { NODE *temp = head; if (temp == NULL) { printf("List is empty!\n"); return; } printf("Linked List is\t"); while (temp != NULL) { printf("%d--> ", temp->data); temp = temp->next; } printf("NULL\n"); } int main() { head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = NULL; printList(); printf("Middle element is\t%d", middle(head)); return 0; }
$gcc mid.c $ ./a.out Linked List is 1–> 2–> 3–> 4–> 5–> NULL Middle element is 3 $ |
If you like the post Find the middle of a given linked list in C, please share your feedback!
also see
C Programming language |
Go Programming language |
Linked List | Array |
Simplification | Queue |
DBMS | Reasoning |
Aptitude | HTML |