middle of linked list

How will you find the middle of the linked list?

Comments

  1. p=head;
    q=head;
    if(q->next->next!=NULL)
    {
    p=p->next;
    q=q->next->next;
    }
    printf("The middle element is %d",p->data);

    ReplyDelete
  2. There is a problem in the above code.It does not work if there is a single node,or there are odd no of nodes.
    it should be like this:


    int middle(struct node *head)
    {
    p=head;
    q=head;
    if(head->next==NULL)
    return (p->data);
    else
    while(q->next->next!=NULL)
    {
    p=p->next;
    if(q->next!=NULL)
    q=q->next->next;
    else
    return (p->data);
    }
    return(p->data);
    }

    ReplyDelete
  3. @kamakshi this code will work for every value except when your list has only one node.for that you will have to add check :
    p=head;
    q=head;
    if(p->link == NULL)
    printf("The middle element is %d",p->data);
    else
    {
    if(q->link->link!=NULL)
    {

    p=p->link;
    q=q->link->link;
    }
    printf("The middle element is %d",p->data);

    ReplyDelete

Post a Comment

Popular posts from this blog