繁体   English   中英

为什么在我的 C 程序中找不到无限循环在链表中搜索? 该程序有效

[英]Why can't I find the infinite loop in my C program to search in a linked list? The program works

这是我在链表中搜索元素的程序。 我被告知我的代码中有一个无限循环。 我不知道在哪里。 该程序适用于我,它不会一直循环给我。 我实在想不通。 如果有人对我应该查看代码的哪一部分来解决问题有任何建议或想法,请告诉我。 我真的很难过。

struct node
{
    int a;
    struct node *next;
};


void generate(struct node **head, int num)
{
    int i;
    struct node *temp;

    for (i = 0; i < num; i++)
    {
        temp = (struct node *)malloc(sizeof(struct node));
        temp->a = rand() % num;

        if (*head == NULL)
        {
            *head = temp;
            temp->next = NULL;
        }
        else
        {
            temp->next = *head;
            *head = temp;
        }
        printf("%d    ", temp->a);
    }
}

void search(struct node *head, int key, int index)
{
    while (head != NULL)
    {
        if (head->a == key)
        {
            printf("Key found at Position: %d\n", index);
        }

        search(head->next, key, index - 1);
    }
}

void delete(struct node **head)
{
    struct node *temp;
    while (*head != NULL)
    {
        temp = *head;
        *head = (*head)->next;
        free(temp);
    }
}

int main()
{
    struct node *head = NULL;
    int key, num;

    printf("Enter the number of nodes: ");
    scanf("%d", &num);
    generate(&head, num);
    printf("\nEnter key to search: ");
    scanf("%d", &key);
    search(head, key, num);
    delete(&head);
}

看你search function:

void search(struct node *head, int key, int index)
{
    while (head != NULL)
    {
        if (head->a == key)
        {
            printf("Key found at Position: %d\n", index);
        }
        search(head->next, key, index - 1);
    }
}

现在,暂时忽略while循环中发生的两个“动作”,只考虑是什么停止了循环执行。 假设(在第一次调用函数时), head的值不是NULL ,循环什么时候停止? 当然,当head变成NULL - 但你永远不会在那个循环中改变head的值! 并且对search的递归调用不会在当前运行的 function 中改变它。 所以这是一个无限循环。

您需要做的是在循环内将head->next分配给head ,如下所示:

void search(struct node *head, int key, int index)
{
    while (head != NULL)
    {
        if (head->a == key)
        {
            printf("Key found at Position: %d\n", index);
        }
        head = head->next; // If list is properly formed, this will get to NULL
        search(head, key, index - 1); // Now we don't need to use the ->next here
    }
}

此外,如果您只想找到第一次出现的键,您可以在printf之后添加一个return语句; 就目前而言,您将打印所有匹配项 - 但这可能是您想要的。

正如另一个答案中提到的,问题是因为您在head不是 null 指针时循环,但您从不修改head所以它永远不会成为 null 指针。

但是search function 还有另一个问题:您需要决定是使用循环还是使用递归来迭代列表。 你不应该同时使用两者。

要么使用循环

while (head != NULL)
{
    if (head->a == key)
    {
        printf("Key found at Position: %d\n", index--);
    }
    head = head->next;
}

或者使用递归

if (head != NULL)
{
    if (head->a == key)
    {
        printf("Key found at Position: %d\n", index);
    }
    search(head->next, key, index - 1);
}

我猜你真的打算做最后一个选择,但错误地使用了while不是if

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM