C Simple LinkedList

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

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

我的Node的结构

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中构造一个空节点first = 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只是指向随机内存,最终导致分段错误。

我只是不知道还有什么地方可以转向。 先谢谢你!

这个块完全没有意义:

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

可能你想移动第first = malloc(sizeof(Node)); 在街区内。 它会工作,但它完全没必要,因为它在逻辑上等于else块。 所以你可以在那里留下第二块:

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

还有一点 – 你应该添加error handling,以防malloc不足,所以你应该检查temp == NULL并相应地行动(从函数返回NULL或者其他……)。

对于初学者来说,即使是函数的第一个语句也是错误的,因为first会覆盖参数的值。

 Node* addFront(Node* first, double x, double y) { first = malloc(sizeof(Node)); //... 

该function可以通过以下方式查看

 Node * addFront( Node *first, double x, double y ) { Node *temp = malloc( sizeof( Node ) ); if ( temp != NULL ) { temp->x = x; temp->y = y; temp->next = first; first = temp; } return first; } 

或者使用测试代码

 Node * addFront( Node *first, double x, double y ) { Node *temp = malloc( sizeof( Node ) ); if ( temp != NULL ) { temp->x = x; temp->y = y; temp->next = first; first = temp; } // start pf inline test size_t size = 0; for ( Node *current = first; current != NULL; current = current->next ) { printf( "(%.4f, %.4f)\n", current->x, current->y ); ++size; } printf( "Size: %zu\n", size ); // end pf inline test return first; }