这就是代码。每当我尝试更改 for 循环中的值时,它总是显示 3 作为中间节点。我似乎遗漏了一些东西,但我看不到错误。
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *find_middle_node(struct node *head)
{
struct node *slow = head;
struct node *fast = head;
while (fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
int main() {
struct node *head = NULL;
struct node *temp;
// create a linked list
head = malloc(sizeof(struct node));
head->data = 1;
head->next = NULL;
temp = head;
for (int i = 0; i <= 89; i++) {
struct node *new_node = malloc(sizeof(struct node));
new_node->data = i;
new_node->next = NULL;
temp->next = new_node;
temp = new_node;
}
// find the middle node
struct node *middle_node = find_middle_node(head);
// print the middle node
printf("The middle node is %d\n", middle_node->data);
return 0;
}
我希望看到这段代码有什么问题。
可能不是您正在寻找的答案,但您的代码正在按预期运行。您是否检查过您正在运行正确的二进制文件或已重新编译?
逻辑是正确的,当节点数量为奇数时,总是向上取整。
示例:假设您有 75 个元素。 75 美元/2 = 37.5 美元。这将返回 38,因为当存在奇数元素时,
fast
总是会超出范围。它将最终位于列表中最后一个节点所指向的指针位置。
我希望这能澄清你的问题。