How to find middle node of a Linked List in C Linux Code

/*C Linux code for finding the middle of a linked list.
Method-1- count the node and the count/2 th element is the middle
element of the Linked List.
Methode 2:- take two pointers advance one by one and the other by 2.
When fast pointer reaches end of the loop the slow reaches to middle
node of the LinkedList.*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head=NULL;
void insert(struct node **,int d);
void display(struct node *);
void findMiddle(struct node *);

int main()
{
insert(&head,10);
insert(&head,20);
insert(&head,30);
insert(&head,40);
insert(&head,50);
display(head);
findMiddle(head);

printf("\n");
return 0;
}
void insert(struct node **head,int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=(*head);
(*head)=newnode;
}
void display(struct node *head)
{
while(head)
{
printf("%d ",head->data);
head=head->next;
}
}
void findMiddle(struct node *head)
{
struct node *slow=head;
struct node *fast=head;
// if(head)
// {
while((fast->next!=NULL) && (fast->next->next!=NULL))
{
slow=slow->next;
fast=fast->next->next;
}
// }
printf("\nThe middle node is:%d ",slow->data);
}
/*

60 50 40 30 20 10
The middle node is:40

*/

No comments:

Post a Comment