c - 在链表中查找中间元素时出现段错误

标签 c pointers linked-list segmentation-fault

我试图找到链表的中间元素,但遇到段错误,并且我不确定出了什么问题。这是我对hare兔子算法的实现:

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

请大家帮忙。

最佳答案

您的问题在行中:

fast = fast->next->next;

假设链表中有两个元素:A -> B -> NULL,首先执行 fast = fast->next,结果是快速指向 B 节点。

当你进入while循环时,你尝试获取B->next->next,结果是NULL->next,这显然不存在.

这个实现是完全错误的,你应该确保避免这种情况。 while 可以改为:

while(fast!=NULL && fast->next != NULL)

这样就可以解决这个问题。

请记住,如果有一对元素,您总是会得到中间更左边的元素。因此,在 A -> B -> NULL 中,您将获得节点 A

关于c - 在链表中查找中间元素时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44166072/

相关文章:

C:由 malloc 函数生成的空闲临时数组

c - 使用宏分配内存不好吗?

c++ - c++链表不再占用Ram空间?

c - 使用分配在堆栈上的数组从不兼容的指针类型警告中初始化

c - 为什么会出现内存泄漏(此初始化导致的段错误)?

c++ - 堆栈溢出与我的析构函数

c - 使用 block 特殊文件/设备来实现文件系统

c - 在 C 中查找函数调用者

c++ - 正确使用 offsetof 宏

c - 在我不应该的情况下在没有警告的情况下获得分配?