#include #include #include "studlist.h" int main() { Record r; int i; /* initialize */ head = make_1node( r, NULL ); listprint(); /* insert list member */ /* CTL+D to escape this loop */ while (1) { printf("Insert new student data: (ID Surname Givenname Age) -> "); if (scanf("%d %s %s %d", &r.id, r.surname, r.givenname, &r.age) != 4) { printf("\n"); break; } if (insert(r) == NULL) { printf("ID %d is already on the list!\n", r.id); } listprint(); } printf("\n"); return 0; } /* First find item r */ /* if it doesn't exist, insert it after head */ /* return new node(inserted), NULL(already exist) */ NodePointer insert(Record r) { NodePointer newnode; if (finditem(r.id) == NULL) { newnode = make_1node(r, head->next); /* 新しいノードを作成 */ head->next = newnode; /* headの下に新しいノードをつなぐ */ return newnode; } else return NULL; } /* print all items in the list from head to tail */ void listprint(void) { NodePointer n; printf("Head - \n"); for(n = head->next; n != NULL; n = n->next){ printf(" %7d %-12s %-12s %d\n", n->data.id, n->data.surname, n->data.givenname, n->data.age); } printf("\n"); } /* 引数にidの値を与えて検索する関数 */ NodePointer finditem(int sid) { NodePointer n; for (n = head; n->next != NULL; n = n->next) { /* headの下から順にポインタnextをたどる */ if (n->next->data.id == sid) return n; /* sidと同じ値が見つかったら一つ手前のノードを指すポインタを返す */ } return NULL; } NodePointer make_1node(Record r, NodePointer p) { NodePointer n; if ((n = (NodePointer) malloc(sizeof(struct node)) ) == NULL) { printf("Error in memory allocation\n"); exit(8); } n->data = r; n->next = p; return n; }