我正试图将节点插入链表对象的头中,但更新后的头似乎不会反映在其他函数中。
我的教授已经指出,我们的插入函数需要一个List结构,而不是指向List结构的指针,但List结构包含一个指向节点的指针——头。
typedef struct Node {
void *Object;
struct Node *next;
} Node;
typedef struct{
Node *head;
} List;
我的insertAtHead函数类似于:
int insertAtHead(void* data, List list) {
int error = 0;
Node * head = list.head;
Node * newNode = createNode(data, &error);
newNode->next = head;
list.head = newNode;
return error; }
Node * createNode(void * Object, int * error) {
Node *pointer;
pointer = malloc(sizeof(Node));
if (pointer == NULL) {
*error = 1;
return NULL;
}
pointer->Object = Object;
pointer->next = NULL;
*error = 0;
return pointer;
}
然而,我的getSize函数打印0——它只找到我在initList中使用的虚拟节点。
int getListLength(List list) {
Node * head = list.head;
int i = 0;
while (head->next != NULL) {
printf("Testn");
i++;
head = head->next;
}
return i;
}
List initList(int * error) {
int * q = malloc(sizeof(int));
*q = 1;
// I use an integer here solely to prove
List list = {createNode(q, error)};
return list;
}
我很困惑自己做错了什么。我怀疑存在一些传递值/引用的恶作剧,但我在所有函数中都使用列表来处理头指针。如果我能做些什么来进一步澄清,请告诉我。非常感谢。
此函数
int insertAtHead(void* data, List list) {
int error = 0;
Node * head = list.head;
Node * newNode = createNode(data, &error);
newNode->next = head;
list.head = newNode;
return error; }
处理的副本,该副本用作List类型的参数对象。因此,更改副本不会反映在原始对象上。
您需要通过指向原始对象的指针通过引用传递该对象
int insertAtHead(void* data, List *list) {
int error = 0;
Node * newNode = createNode(data, &error);
if ( error == 0 )
{
newNode->next = list->head
list->head = newNode;
}
return error;
}
如果不允许通过引用传递List类型的原始对象,则必须从函数返回List类型的修改对象,例如
List insertAtHead(void* data, List list, int *error ) {
Node * newNode = createNode(data, error);
if ( *error == 0 )
{
newNode->next = list.head
list.head = newNode;
}
return list;
}
您需要将返回的对象分配给调用者中List类型的对象。
还有这个功能
List initList(int * error) {
int * q = malloc(sizeof(int));
*q = 1;
// I use an integer here solely to prove
List list = {createNode(q, error)};
return list;
}
没有道理。
最初,该列表应该为空。因此,列表的初始化包括数据成员head
到NULL
的初始化。
此外,函数getListLength
至少应该看起来像(如果不允许通过引用传递列表(
int getListLength(List list) {
Node * head = list.head;
int i = 0;
while (head != NULL) {
printf("Testn");
i++;
head = head->next;
}
return i;
}