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

C Program to print the middle of a given linked list:-
 ->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

 #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;

}

void TraverseTillMiddle(struct node *head)
{
struct node *mid,*current;

mid=head;
int count=0;
current=head;
while(current->next!=0)
{
current=current->next;
if(count%2!=0)
{
mid=mid->next;
}
count++;
}

printf("%d\n",mid->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);
insert(&head,7);
insert(&head,8);
insert(&head,9);
insert(&head,10);

TraverseTillMiddle(head);

}

Related Posts