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'逐个带到头上,所以我写这个函数但是当我调试时它给出了分段错误该计划
答案 0 :(得分:0)
temp->next!=current
,否则 temp==temp->next
将永远不会成真。
试试这个:
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;
}