Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

c - traverse pointer from last node to first

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...