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; }
我有链表和’head’指针保持第一个节点,’current’指针保持最后一个节点,我想把’current’逐个带到头,所以我写这个函数但是当我调试程序时它给出了分段错误
temp->next!=current
除非temp==temp->next
否则temp->next!=current
永远不会成立。
试试这个:
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; }
或者更简化:
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; }
为了使其更安全,请确保temp
不是NULL
以避免在current
无效的情况下运行时错误。
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; }
也许你想要这个:
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; }
以上就是c/c++开发分享遍历指针从最后一个节点到第一个节点相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/519224.html