|
> 自己参照構造体を基本から学習しようと
> 例題では、打ち込んだ順番の最後から逆順にリスト表示されているのを、
> トップから順番に表示する仕様に変えようと頑張ってみたのですが、
struct list *reverse_list(struct list *head)
{
struct list *next, *prev = NULL;
if (head == NULL) return NULL;
for (;;) {
next = head->next;
head->next = prev;
prev = head;
if (next == NULL) return head;
head = next;
}
}
このような、リストを反転する関数を用意して、
head = reverse_list(head);
とするのもひとつの手です。
既にヒントが出ている、リストの末尾に追加するやり方では、add_list を
次のように変更すればできます。
struct list *add_list(int key, char *name, struct list *tail)
{
struct list *p = malloc(sizeof *p);
if (p == NULL) printf("out of memory\n"), exit(1);
p->key = key;
strcpy(p->name, name);
p->next = NULL;
if (tail != NULL) tail->next = p;
return p;
}
呼び出しは次のようになります。
struct list *head = NULL; /* 先頭ポインタ */
struct list *tail = NULL; /* 末尾ポインタ */
while (scanf("%d %s", &key, name) == 2) {
tail = add_list(key, name, tail);
if (head == NULL) head = tail;
}
|