gpt4 book ai didi

C 简单链表

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:23 26 4
gpt4 key购买 nike

我在网上看了很多不同的问题,但无法弄清楚我做错了什么。我现在可能正朝着错误的方向前进,因为我尝试了很多不同的事情。

我只是想在 C 中制作一个简单的单链表。我似乎无法弄清楚如何使列表保持连接。

我的节点的结构

typedef struct node
{
double x; // x-coordinate of this point in the tour
double y; // y-coordinate of this point in the tour
struct node* next; // Pointer to the next node in the linked list
} Node;

这是我创建列表的代码,我在 main 中首先构造了一个空节点 = NULL

Node* addFront(Node* first, double x, double y) {   

first = malloc(sizeof(Node));
if (first == NULL) {
first->x = x;
first->y = y;
first->next = NULL;
}
else {
Node * temp = malloc(sizeof(Node));
temp->x = x;
temp->y = y;
temp->next = first;
first = temp;
}
//Temp testing
int size = 0;
Node * current = first;
while (current->next != NULL) {
printf("(%.4f, %.4f)\n", current->x, current->y);
current = current -> next;
size++;
}
printf("Size: %d\n", size);

return first;
}

一些注意事项:

检查 first 是否为 null 应该是不必要的......列表应该能够只使用 else 语句构建。 (我的想法)

添加 if/else 语句后,我得到了一个似乎是 C 指向随机内存的无限循环,最终导致段错误。

我只是不知道还能去哪里。非常感谢您!

最佳答案

这个 block 根本没有意义:

 first = malloc(sizeof(Node));
if (first == NULL) {
first->x = x;
first->y = y;
first->next = NULL;
}

可能您想将 first = malloc(sizeof(Node)); 移动到 block 内。它可以工作,但是完全没有必要,因为它在逻辑上等同于 else block 。所以你可以只留下第二个 block :

    Node * temp = malloc(sizeof(Node));
temp->x = x;
temp->y = y;
temp->next = first;
first = temp;
return first;
// or rather return temp directly

还有一点 - 你应该添加错误处理以防 malloc 内存不足,所以你应该检查 temp == NULL 并采取相应的行动(返回NULL 来自函数或其他...)。

关于C 简单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36302590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com