您还没有按返回值返回列表的新头部。如果插入一个节点,则必须为一个节点分配内存。不要忘了第一个节点的初始化成员prev
最后节点与NULL
成员link
:
node* insert(char* str, node* head)
{
node* new_node = malloc(sizeof(struct node));
assert(new_node != NULL);
new_node->value = strdup(str);
new_node->link = NULL; // successor of new node is NULL
if (head == NULL)
{
new_node->pev = NULL; // prdecessor of first node is NULL
head = new_node;
return new_node; // head was NULL, return new head
}
node *lastNode = head; // go to last node of list
while (head->link != NULL)
lastNode = lastNode->link; // step one forward
lastNode->link = new_node; // successor of last node is new node
new_node->prev = lastNode; // predecesor of new node is last node
return head;
}
-
node *head = NULL;
head = insert("abc", head);
head = insert("def", head);
另一个解决方法是使用一个在输出放慢参数你在功能insert
放慢参数head
:
void insert(char* str, node** head)
// ^^ in and output parameter
{
node* new_node = malloc(sizeof(struct node));
assert(new_node != NULL);
new_node->value = strdup(str);
new_node->link = NULL; // successor of new node is NULL
node* prev = NULL;
node* act = *head;
while (act != NULL) // go to last node in list
{
prev = act;
act = act->link; // step one forward
}
new_node->prev = prev; // predecessor of new node is last node or NULL
if (prev == NULL)
*head = new_node; // new node is the first node in list,
// write the new node back to head
else
prev->link = new_node; // successor of last node is new node
}
-
node *head = NULL;
insert("abc", &head);
insert("def", &head);
“这是否工作?测试它,你会知道。通过查看代码很难看出它是否工作 - 除非你是真正的专家。 – Ian
这也不是所有的代码。只有你有足够的代码才能知道它是否有效。 – e0k
注意'head = head-> link;'在函数范围内修改'head'的值,但不在它之外。函数在参数副本上工作。为了解决这个问题,即使它已经是一个指针,也要通过指针传递'head'。尝试'void insert(char * str,node ** head)'和'if(* head == NULL)...' – francis