嗨,我正在编写这段代码,它需要 3 个字段,将其存储到结构中,但我不知道如何创建节点,函数 print_planet_list() 应该遍历链表并打印输出。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* the struct */
typedef struct{
char name[128];
double dist;
char description[1024];
} planet_t;
/* have to write a definition here */
typedef struct planet_node {
???; /* what to write here? */
} planet_node;
/* Print a list of planets pointed to by ptr */
void print_planet_list(planet_node *ptr){
while(ptr != NULL){
printf("%15s %10.2f %s\n",
new[i].name,
new[i].dist,
new[i].description);/* not sure if its correct */
}
printf("\n");
}
int main(){
char buf[64];
planet_node *head = NULL;
int quit = 0;
do {
printf("Enter planet name (q quits): ");
scanf("%s",buf);
if((strcmp(buf,"q")==0)){
quit = 1;
}
else{
planet_node *new = (planet_t *) malloc(sizeof(planet_t)*? );
strcpy(???);
printf("Enter distance and description: ");
scanf(" %lf ", new[i].dist);
gets(new[i].description);
ptr->head; /* Link new node to head */
???; /* Set the head to the new node */
}
} while(!quit);
printf("Final list of planets:\n");
print_planet_list(head);
while(head != NULL){
planet_node *remove = head;
head = (*head).next;
free(remove);
}
}
我想要的输入是:
输入行星名称(q 退出):地球输入距离和描述:0.9 友好和好客输入行星名称(q 退出):火星输入距离和描述:1.05 非常国际化
输出:
火星 1.05 非常国际化 地球 0.90 友善好客