本帖最后由 jackz007 于 2022-9-18 13:19 编辑 #include <stdio.h>
#include <stdlib.h>
struct STU {
int age ;
char name[20] ;
struct STU * next ;
} ;
struct STU * input(struct STU * x)
{
struct STU * p ;
if((p = (struct STU *) malloc(sizeof(struct STU)))) {
printf("input name please : ") ;
scanf_s("%s", & p -> name , 20) ;
printf("input age please : ") ;
scanf_s("%d", & p -> age) ;
p -> next = x ;
} else {
fprintf(stderr , "failure of malloc():\n") ;
}
return p ;
}
void disp(struct STU * x)
{
for(; x ; x = x -> next) printf("name : %20s , age : %2d\n" , x -> name , x -> age) ;
}
void destroy(struct STU * x)
{
struct STU * p ;
for(; x ;) {
p = x ;
x = p -> next ;
free(p) ;
}
}
int main(void)
{
struct STU * L = NULL ;
int i , n ;
printf("input the number of people please : ") ;
scanf_s("%d" , & n) ;
for(i = 0 ; i < n ; i ++) L = input(L) ;
disp(L) ;
destroy(L) ;
system("pause") ;
}
编译、运行实况:D:\[00.Exerciese.2022]\C>g++ -o x x.c
D:\[00.Exerciese.2022]\C>x
input the number of people please : 5
input name please : abc
input age please : 18
input name please : def
input age please : 19
input name please : efg
input age please : 20
input name please : fgh
input age please : 21
input name please : ghi
input age please : 22
name : ghi , age : 22
name : fgh , age : 21
name : efg , age : 20
name : def , age : 19
name : abc , age : 18
请按任意键继续. . .
D:\[00.Exerciese.2022]\C>
|