Write a C Program to print the middle of a given linked list(Method 1 )

C Program to print the middle of a given linked list:-
 1. Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2  and return the node at count/2.(Work for  Both  Odd and Even no.of Node in Linked List)

#include<stdio.h>
#include<stdlib.h>

struct node{

int data;
struct node *next;
};

void insert(struct node **head,int new_data)
{
struct node *new_node;
new_node=(struct node*)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=*head;
*head=new_node;

}

int count(struct node *head)
{
int count=0;
struct node *current;
current=head;
while(current->next!=0)
{
current=current->next;
count++;
}
return count;
}

void TraverseTillMiddle(struct node *head,int n)
{
int x=1;  //loop run until mid of linked list not found.
while(x!=n)  
{
head=head->next;
x++;
}
printf("%d\n",head->data);
}

main()
{

struct node *head;
head=(struct node*)malloc(sizeof(struct node));

insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);
insert(&head,5);
insert(&head,6);

int n=count(head);

if(n%2!=0)        //if no.of element in linked list is odd.
{
n=(n+1)/2;
}

else               //if no.of element in linked list is even.
{
n=n/2;
}

TraverseTillMiddle(head,n);

}


Related Posts