【发布时间】:2021-01-09 04:25:57
【问题描述】:
我的链表练习要求我创建一个结构数组,其中包含人名(定义为 4 个字符的名称)以及该人与我的距离。
创建 3 个数组元素后,我将每个人和他的距离放入一个链表中。
我已经制作了数组并按原样成功打印了它,但是制作列表时遇到了麻烦。
我的代码如下,非常感谢一个让代码启动并运行的解决方案。
typedef struct Node
{
int dist;
char name[4];
struct Node* next;
}Node;
void main()
{
int i;
Node arr[3];
for (i = 0; i < 3; i++)
{
printf("Enter name: \n");
scanf("%s", arr[i].name);
printf("Enter distance: \n");
scanf("%d", &arr[i].dist);
}
printf("Basic printing of the ARRAY:");
for (i = 0; i < 3; i++)
{
printf("Distance of %s is: %d\n", arr[i].name, arr[i].dist);
}
printf("\n\n\n");
Node* head;
Node* tail;
head = tail = NULL;
head = malloc(sizeof(Node));
tail = malloc(sizeof(Node));
for (i = 0; i < 3; i++)
{
if (i == 0)
{
head->dist = arr[i].dist;
head->name[4] = arr[i].name;
tail = head;
}
else
{
tail->next = malloc(sizeof(Node));
tail = tail->next;
tail->next = NULL;
tail->dist = arr[i].dist;
tail->name[4] = arr[i].name;
}
}
Node* temp;
temp = head;
printf("Now we print the list\n");
for (i = 0; i < 3; i++)
{
printf("Distance of %s is: %d\n", temp->name, temp->dist);
temp = temp->next;
}
【问题讨论】:
标签: arrays c struct linked-list