#include /*構造体の定義*/ struct Cell { int number; struct Cell *next; }; /*プロトタイプ宣言*/ void p_list(struct Cell *topcell_ptr); int main(void) { /*変数の定義*/ int n; /*入力された数字を受けるための変数*/ /*rootの定義*/ struct Cell *root; /*新しいセルを指すポインタの定義*/ struct Cell *newcell_ptr; /*最新の一つ前のセルを指すポインタの定義*/ struct Cell *lastcell_ptr; /*rootはとりあえずNULLを指す*/ root=NULL; /*プログラムの説明*/ printf("整数をいくつか入力してください。\n0が入力されると終了します。\n"); while(1){ /*無限ループ*/ /*値の入力*/ scanf("%d",&n); if(n==0)break; /*0が入力されたらループ脱出*/ /*構造体変数とポインタの作成*/ newcell_ptr=(struct Cell*)malloc(sizeof(struct Cell)); /*新しくできた構造体変数内のint型変数に、 入力された値を代入する*/ newcell_ptr->number=n; /*ポインタの操作*/ if(root==NULL){ /*rootがNULLの時(つまり初回)は、rootとnewcell_ptr->nextの値を入れ替える*/ root=newcell_ptr; newcell_ptr->next=NULL; /*次のために、lastcell_ptrに今newcell_ptrが指している値を記憶させる*/ lastcell_ptr=newcell_ptr; } else{ /*初回以外のとき*/ /*直前のセル内のポインタに、新しく作ったセルを指させる*/ lastcell_ptr->next = newcell_ptr; /*最新のセル内のポインタはNULLを指す*/ newcell_ptr->next = NULL; /*次のために、lastcell_ptrに今newcell_ptrが指している値を記憶させる*/ lastcell_ptr=newcell_ptr; } } /*線型リストの出力*/ p_list(root); return 0; } /*線型リストを先頭から順に画面に印字する*/ void p_list(struct Cell *topcell_ptr) { while(topcell_ptr!=NULL){ printf("%d ", topcell_ptr->number); topcell_ptr= topcell_ptr->next; } }