0
该程序应该从用户获取一个项目并将其放在列表的末尾。C程序链表添加到末尾
如果我输入:batteries, flashlight and pens as the item name.
顺序应该是
1 batteries
2 flashlight
3 pens
但是顺序是:
3 pens
2 flashlight
1 batteries
我的代码是:
struct item *end_of_list(struct item *inventory)
{
struct item *cur, *new_node;
new_node = malloc(sizeof(struct item));
if (new_node == NULL) {
printf("malloc failed\n");
return inventory;
}
printf("Enter item ID: \n");
scanf("%d", &new_node->number);
for(cur=inventory; cur != NULL; cur = cur->next) {
if (cur != NULL && new_node->number == cur->number) {
printf("item already exists: %s\n",new_node->item_name);
free(new_node);
return inventory;
}
}
printf("Enter item name: \n");
printf("%s, new_node->item_name")
new_node->next = NULL;
if (inventory == NULL) {
inventory = new_node->next;
} else {
while (new_node->next != NULL) {
new_node = new_node->next;
}
new_node->next = inventory;
}
return new_node;
}
非常感谢!有效 – lodam