我有一个奇怪的问题。我有这段代码,但是没有用。奇怪的是,在函数内部,列表已更改(printf命令表明了这一点),但是当调用此函数时,什么都不会添加到列表中(我的列表不为空)。
void pushToList(node* list, int val) {
node* newNode = (node*) malloc(sizeof(node));
newNode->value=val;
newNode->next = list;
list = newNode;
printf("here, list->value = %d \n", list->value);
printf("here, list->next->value = %d \n", list->next->value);
}
// ----------------------------------
// if (list==NULL) {
// newNode->next = NULL;
// list = newNode;
// } else {
// newNode->next = list;
// list = newNode;
// }
例如,在我的主要函数中,我将此函数称为:
node* node1;
pushToList(node1, 1111);
这是我的struct和typedef在单独的头文件中(我已将其包含在函数文件中):
#ifndef STACKELEMENT_H
#define STACKELEMENT_H
struct stackElement {
int value;
struct stackElement* next;
};
typedef struct stackElement node;
#endif /* STACKELEMENT_H */
另一个怪异的行为是我具有以下用于追加项目的功能,并且该功能仅在我的列表不为空的情况下有效:
int appendtoList(node* head, int val) {
node* current = head;
node* newNode = (node*) malloc(sizeof (node));
if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for the new node\n");
exit(-1);
}
newNode->value = val;
newNode->next = NULL;
while (current->next) {
current = current->next;
}
current->next = newNode;
// if (head->next == NULL) {
// head->next = newNode;
// } else {
// while (current->next != NULL) {
// current = current->next;
// }
// current->next = newNode;
// }
//
return 0;
}
最佳答案
在函数中使用node ** list作为参数类型。
当您将指向结构节点* x之类的函数的指针传递给
void max(结构节点* p);
指针由值AND传递
如果您想真正操纵x指向的内容,以使用struct node **作为参数类型并将&x传递给函数。
同样的逻辑也适用于您的问题。