此代码仅将一个元素添加到列表的末尾(仅创建 head 元素,之后什么也没有)。我的程序有什么问题?我应该在函数中传递两个项目,head 和 item 还是只传递一个?
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct MyList
{
int x;
int y;
struct MyList * next;
}List;
typedef List * Item;
void AddEnd(Item * head);
void PrintList(Item * head);
int main(void)
{
int response;
Item head;
head = NULL;
while(1)
{
printf("1- Print, 2 - Add to End, 3 - exit\n");
scanf("%d", &response);
switch(response)
{
case 1: PrintList(&head); break;
case 2: AddEnd(&head); break;
case 3: return 0;
}
}
return 0;
}
void PrintList(Item * head)
{
Item temp;
temp = *head;
while(temp != NULL)
{
printf("%d %d\n", temp->x, temp->y);
temp = temp->next;
}
}
void AddEnd(Item * head)
{
Item new, temp;
new = (Item)malloc(sizeof(new));
printf("Enter x and y: ");
scanf("%d %d", &new->x, &new->y);
new->next = NULL;
if(*head == NULL)
{
*head = new;
}
else
{
temp = *head;
while(temp != NULL)
{
temp = temp->next;
}
temp = new;
}
}
我刚试过的这段代码也不起作用:
void AddEnd(Item * head, Item * item)
{
Item new, temp;
new = (Item)malloc(sizeof(new));
printf("Enter x and y: ");
scanf("%d %d", &new->x, &new->y);
new->next = NULL;
if(*head == NULL)
{
*head = new;
}
else
{
temp = *head;
while(temp != NULL)
{
temp = temp->next;
}
temp = new;
*item = temp;
}
}
最佳答案
在 else
子句的 AddEnd
函数中,当您退出 while 循环时,temp
现在是 NULL
。但是,它之前的元素仍然指向 NULL
。
尝试类似的东西
temp = *head;
if (temp->next == NULL) {
temp->next = new;
} else {
while((temp->next) != null) {
temp = temp->next;
}
temp->next = new;
}
在您的 else
子句中。
(这个,以及你对其他人引用的 malloc 的理解的明显问题, 阅读你的 typedefs a更仔细一点,new
应该是一个 Item *
并且 malloc 调用应该是 malloc(sizeof(Item))
。你也不需要转换 malloc 的返回值(事实上,如果你这样做,会发生一些陷阱)。new
应该 实际上是一个 Item
(因为它是一个指向 List
结构的指针,并且您有typedef List* Item
).尝试使用 new = malloc(sizeof(List));
并将 new
声明为 List *
类型。 (typedef List * Item
使您的代码难以阅读;它变得不太清楚什么是指针,什么不是。)
关于无法将项目添加到链接列表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18028047/