В основном в приведенном ниже коде я пытаюсь вставить некоторые имена и некоторые возрасты в список и распечатать их. Однако моя программа печатает только имя и возраст списка. Какие-либо предложения?Элементы печати списка в C
#include <stdio.h>
#include <stdlib.h>
/* these arrays are just used to give the parameters to 'insert',
to create the 'people' array
*/
#define HOW_MANY 7
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
typedef struct person
{
char *name;
int age;
struct person *next;
}Person;
Person *headp = NULL;
static Person* insert(Person *p, char *name, int age)
{
p = (Person*)malloc(sizeof(Person));
if (p == NULL)
abort();
p->name = name;
p->age = age;
p->next = headp;
return p;
}
int main(int argc, char **argv)
{
Person *people=headp;
for (int i = 0; i < 7; i++)
{
people = insert (people, names[i], ages[i]);
}
while (people != NULL)
{
printf ("name: %s, age: %i\n", people->name, people->age);
people= people->next;
}
return 0;
}
Он работает .... но он печатает элементы в обратном порядке ... т.е. первый элемент является последним ... –
Затем измените 'for (int i = 0; i <7; i ++)' to 'for (int i = 6; i> = 0; i -)' –
@ RalucaDamarisLupeş : Как это удивительно? Вы создали свою функцию 'insert', чтобы действовать как' prepend', а не 'append'. –