|
学校の課題なんですが何とか終ったけど最後の
p_add->nextp=p_top;
p_top=p_add;
のところが実は違うらしいのです。
2行じゃ終らないとかって聞いたのですが自分ではこれでいいと思うので
どう違うのかがわかりません。
なにが違うのか教えて下さい。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 128
typedef struct pl{
struct pl *nextp;
int number;
char *name;
} PlayerList;
PlayerList *readNumberandName();
void printList(PlayerList *);
void freeList(PlayerList *);
void printListforDebug(PlayerList *, char *);
PlayerList *addPlayertoList(PlayerList *, PlayerList *);
int main ()
{
PlayerList dummy = {
NULL,
0,
"ダミー"
};
PlayerList *p_listtop = &dummy, *p_new;
while ((p_new = readNumberandName()) != NULL ) {
p_listtop = addPlayertoList(p_listtop, p_new);
}
printList(p_listtop);
freeList(p_listtop);
p_listtop = NULL;
return 0;
}
PlayerList *readNumberandName()
{
char buf[MAX];
int len;
PlayerList *p_pl;
p_pl = (PlayerList *)malloc(sizeof(PlayerList));
if (p_pl == NULL) {
printf("メモリの確保に失敗\n");
exit(-1);
}
p_pl->nextp = NULL;
printf("選手の背番号: ");
if (fgets(buf, MAX, stdin) == NULL) {
free(p_pl);
p_pl = NULL;
return NULL;
}
p_pl->number = atoi(buf);
printf("選手の名前: ");
if (fgets(buf, MAX, stdin) == NULL) {
free(p_pl);
p_pl = NULL;
return NULL;
}
len = strlen(buf);
if (len > 0){
if (buf[len-1] == '\n'){
buf[len-1] = '\0';
len--;
}
}
p_pl->name = (char *)malloc(len+1);
if (p_pl->name == NULL) {
printf("メモリの確保に失敗\n");
free(p_pl);
p_pl = NULL;
exit(-1);
}
strcpy(p_pl->name, buf);
return p_pl;
}
void freeList(PlayerList *p_top)
{
PlayerList *p_pl, *p_next;
for (p_pl = p_top; p_pl->nextp != NULL; p_pl = p_next) {
p_next = p_pl->nextp;
free(p_pl->name);
free(p_pl);
}
}
void printList(PlayerList *p_pl)
{
printf("\n\n");
if (p_pl != NULL ) {
for (; p_pl->nextp != NULL; p_pl = p_pl->nextp)
printf("背番号%2d を持つ選手は %s です\n",
p_pl->number, p_pl->name);
}
printf("\n");
}
void printListforDebug(PlayerList *p_pl, char *message)
{
printf("DEBUG %s:\n", message);
for (; p_pl != NULL; p_pl = p_pl->nextp)
printf("背番号%2d を持つ選手は %s です\n", p_pl->number, p_pl->name);
printf("DEBUG %s:\n", message);
}
PlayerList *addPlayertoList(PlayerList *p_top, PlayerList *p_add)
{
PlayerList *p_pl;
p_add->nextp=p_top;
p_top=p_add;
}
標準入力から背番号と選手名を次々に読み込み、背番号順になるように
リストに追加し、最後に背番号と選手名を昇順に出力する。
プログラムの仕様:
1.次のような自己参照、及び背番号と選手名を持つ構造体 PlayerList を
定義する。
typedef struct pl{
struct pl *nextp;
int number;
char *name;
} PlayerList;
2. リストの先頭にダミーを置く
3. 標準入力から選手の背番号の入力を次々に求め、構造体に格納する。
そしてこの構造体をリストに背番号順に挿入していく。
4. EOF(Ctrl-D)が入力されるとリストの内容を表示して終わる。
|