リスト構造を実現する単純なプログラム
ティーチングアシスタントをやっているので,教えられるように実際に書いてみた.
/* リスト構造を実現する単純なプログラム */ #include <stdio.h> #include <stdlib.h> #include <string.h> struct record { char *name; //名前を格納する領域へのポインタ int score; //点数を格納 struct record *next; //次のレコードへのポインタ }; typedef struct record element; element *first; //先頭の要素へのポインタ #define MAXLEN 128 #define Boolean int #define TRUE 1 #define FALSE 0 char buff[MAXLEN]; void comm_add(); void comm_delete(); void comm_search(); void comm_count(); void comm_list(); int main(void) { first = NULL; while(1) { printf("Command: "); scanf("%s",buff); switch(buff[0]) { case 'a': comm_add(); break; case 'd': comm_delete(); break; case 's': comm_search(); break; case 'c': comm_count(); break; case 'l': comm_list(); break; case 'e': exit(0); break; default: printf("Illegal Command\a\n"); } } } void comm_add() { element *pt; pt = (element *)malloc(sizeof(element)); if(pt==NULL) { printf("malloc error 1\n"); exit(1); } pt->next = first; first = pt; printf("Input name :"); scanf("%s",buff); pt->name = (char *)malloc(sizeof(char)*(strlen(buff)+1)); if(pt->name==NULL) { printf("malloc error 2\n"); exit(2); } strcpy(pt->name,buff); printf("Input score :"); scanf("%d",&pt->score); printf("\n"); } void comm_delete() { char key[MAXLEN]; printf("Delete name :"); scanf("%s",key); element *pt; element *pre_pt=NULL; //一個前のポインタ pt = first; while(pt != NULL) { if(strcmp(key,pt->name)==0) { if(pre_pt==NULL) first = pt->next; else pre_pt->next = pt->next; free(pt->name); free(pt); } pre_pt = pt; pt = pt->next; } printf("\n"); } void comm_search() { char key[MAXLEN]; printf("Search name :"); scanf("%s",key); element *pt; Boolean searchFlag = FALSE; pt = first; while(pt != NULL) { if(strcmp(key,pt->name)==0) { printf("%s's score = %d\n",pt->name,pt->score); searchFlag = TRUE; } pt = pt->next; } if(!searchFlag) printf("%s is not registered\n\n",key); printf("\n"); } void comm_count() { int count = 0; element *pt; pt = first; while(pt != NULL) { count++; pt = pt->next; } printf("count :%d\n\n",count); } void comm_list() { element *pt; pt = first; while(pt != NULL) { printf("%s's score = %d\n\n",pt->name,pt->score); pt = pt->next; } }