To find the middle element of a linklist in single pass.
int getMiddle(struct node *p)
{
int mid;
struct node *p1,*p2;
p1=p2=p;
while(p2->link != NULL && p2->link->link != NULL)
{
p1=p1->link;
p2=p2->link->link;
}
return p1->data;
}
- Take two pointers P1 and P2, both pointed to the first element.
- Increment P1 by 1 and P2 by 2.
- Whenever P2 reaches to the end, P1 will be at the middle of the list"
int getMiddle(struct node *p)
{
int mid;
struct node *p1,*p2;
p1=p2=p;
while(p2->link != NULL && p2->link->link != NULL)
{
p1=p1->link;
p2=p2->link->link;
}
return p1->data;
}
No comments:
Post a Comment