-2
基本上在下面的代碼中,我試圖在列表中插入一些名字和一些年齡並將它們打印出來。但是,我的程序只打印列表的姓氏和年齡。有什麼建議麼?打印列表中的元素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 ++)'改爲'for(int i = 6; i> = 0; i - )' –
@RalucaDamarisLupeş :這是如何令人驚訝?你已經設計了你的'insert'函數,像'prepend'而不是'append'。 –