下のようにdata型の構造体を定義する。

struct data{
  char key;
  struct data *next;
};

data型の構造体のポインタ変数topを作成しリストヘッドとする。下記の出力命令に対し下記の出力結果を得るようにmallocを用いてメモリ確保を行ない、リスト末尾に要素を挿入していくことで、単方向線状リストを作成せよ。

出力命令

    printf("%c\n", top->key);
    printf("%c\n", top->next->key);
    printf("%c\n", top->next->next->key);

出力結果

a
b
c

以下自分のコード

#include<stdio.h>
#include<string.h>
struct data{
  char key;
  struct data *next;
}

  int main()
  {

    struct data *top;

    top = (struct data*)malloc(sizeof(struct data)*(data));
    if(top == NULL){printf("メモりが確保できませんでした。\n"); return 1;     }
    strcpy(top->key, 'a');
    top->next = (struct data*)malloc(sizeof(struct data)*(data));
    if(top->next == NULL){printf("メモりが確保できませんでした。\n"); return 1;        }


    top = top->next;
    strcpy(top->next->key, 'b');
    top->next->next = (struct data*)malloc(sizeof(struct data)*(data));
    if(top->next->next == NULL){printf("メモりが確保できませんでした。\n"); 
      return 1;     }
    top = top->next->next;

    strcpy(top->next->next->key, 'c');
    top->next->next->next = NULL;




    printf("%c\n", top->key);
    printf("%c\n", top->next->key);
    printf("%c\n", top->next->next->key);


    return 0;

  }
