2014-09-19

How do you find the middle of a linked list? Write a C program to return the middle of a linked list

Method1
p=head;
q=head;
if(q->next->next!=NULL)
{
p=p->next;
q=q->next->next;
}
printf("The middle element is %d",p->data);
Here p moves one step, where as q moves two steps, when q reaches end, p will be at the
middle of the linked list.

Method2

struct node *middle(struct node *head)
{
struct node *middle=NULL;
int i;
for(i=1; head; head=head->next,i++)
{
if(i==1)
middle=head;
else if ((i%2)==1)
middle=middle->next;
}
return middle;
}
In a similar way, we can find the 1/3 th node of linked list by changing (i%2==1) to
(i%3==1) and in the same way we can find nth node of list by changing (i%2==1) to
(i%n==1) but make sure ur (n<=i).
p=head;
q=head;
if(q->next->next!=NULL)
{
p=p->next;
q=q->next->next;
}
printf("The middle element is %d",p->data);

Here p moves one step, where as q moves two steps, when q reaches end, p will be at the
middle of the linked list.

Method2
struct node *middle(struct node *head)
{
struct node *middle=NULL;
int i;
for(i=1; head; head=head->next,i++)
{
if(i==1)
middle=head;
else if ((i%2)==1)
middle=middle->next;
}
return middle;
}


In a similar way, we can find the 1/3 th node of linked list by changing (i%2==1) to
(i%3==1) and in the same way we can find nth node of list by changing (i%2==1) to
(i%n==1) but make sure ur (n<=i).

0 comments:

Post a Comment

Tools & Plugins

Blog Archive