【发布时间】:2017-05-24 18:30:05
【问题描述】:
我正在尝试查找链接列表的中间元素,但我遇到了分段错误,我不确定出了什么问题。这是我对兔子算法的实现:
//fast slow pointer method
void ptMiddle(struct node **head_ref)
{
struct node *fast = (*head_ref);
struct node *slow = (*head_ref);
fast = fast->next;
while(fast!=NULL)
{
// printf("%d%d",slow->data,fast->data);
slow = slow->next;
fast = fast->next->next;
}
printf("Middle elemnet is:%d\n",slow->data);
}
int main()
{
struct node * head=NULL;
push(&head,1);
push(&head,2);
push(&head,3);
push(&head,4);
printList(&head);
printf("M:%d\n",middleNode(&head)->data);
printf("here");
append(&head,5);
append(&head,6);
printList(&head);
printf("M:%d\n",middleNode(&head)->data);
printf("here");
ptMiddle(&head);
return 0;
}
请帮忙。
【问题讨论】:
-
缺少
push的实现 -
如果
fast->next是NULL,fast->next->next;将失败。 -
以后如果在调试器中运行程序,看看是哪一行使程序崩溃,会省去很多麻烦。另一个好方法是添加
assert()语句,表明您正在执行的操作确实有效。在这里,可能包括assert(head_ref);和assert(slow);。 -
@xsami 我在这里暂时发表了评论,以添加信息(快速),我也将其编辑到问题中(我必须等待同行评审)。它本应以实事求是的方式进行,但必须对“小”编辑进行彻底的推理以确保其被接受。无需为小事故道歉——这不是我想要达到的目标。
标签: c pointers linked-list segmentation-fault