Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

bn_ptr drive_temp(bn_ptr head,bn_ptr temp,bn_ptr current)
{

    while(temp->next!=current)
    {
        temp=temp->next;
        current=temp;
    }
    temp=head;

    return current; 
}

I have linked list and 'head' pointer hold first node , 'current' pointer hold last node,I want to bring 'current' to head one by one ,so I write this function but it gives segmentation fault when I debug the program

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

temp->next!=current will never be true unless temp==temp->next.

Try this:

bn_ptr drive_temp(bn_ptr head,bn_ptr temp,bn_ptr current)
{

    while(temp->next!=current)
    {
        temp=temp->next;
    }
    current=temp; /* get this out of the loop */
    temp=head;

    return current; 
}

or more simplified this:

bn_ptr drive_temp(bn_ptr head,bn_ptr temp,bn_ptr current)
{
    (void)head; /* head isn't used, so put this to avoid warning */
    while(temp->next!=current)
    {
        temp=temp->next;
    }
    /* current and temp will be lost, so assigning to them here is useless */

    return temp; 
}

To make it safer, make sure that temp isn't NULL to avoid runtime error in case of current is invalid.

bn_ptr drive_temp(bn_ptr head,bn_ptr temp,bn_ptr current)
{
    (void)head; /* head isn't used, so put this to avoid warning */
    while(temp != NULL && temp->next!=current)
    {
        temp=temp->next;
    }

    /* temp will be the previous node of current or NULL */
    return temp; 
}

Maybe you want this:

bn_ptr drive_temp(bn_ptr head,bn_ptr current) /* remove temp from the arguments */
{
    bn_ptr temp = head;
    while(temp != NULL && temp->next!=current)
    {
        temp=temp->next;
    }

    /* temp will be the previous node of current or NULL */
    return temp; 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...