読者です 読者をやめる 読者になる 読者になる

はわわーっ

はわわわわっ

連結リスト

c

やってみた。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


struct List {
  int value;
  struct List *next;
};

struct List * new_list(void);
void delete_list(struct List *);
void print_list(struct List *);
void append_elem(struct List *, int);


int main(void)
{
  struct List *list0;
  struct List *list1;

  list0 = new_list();
  list1 = new_list();

  append_elem(list0, 0);
  append_elem(list0, 2);
  append_elem(list0, 4);
  append_elem(list1, 11);
  append_elem(list1, 12);

  print_list(list0);
  print_list(list1);

  delete_list(list0);
  delete_list(list1);

  return 0;
}


struct List * new_list(void)
{
  struct List * head;

  if ((head = malloc(sizeof(struct List))) == NULL) {
    printf("malloc failed\n");
    exit(EXIT_FAILURE);
  }
  head->value = 0;
  head->next = NULL;
  return head;
}

void delete_list(struct List *list)
{
  struct List *p = list->next;

  while (p != NULL) {
    list->next = p->next;
    free(p);
    p = list->next;
  }
  free(list);
}

void print_list(struct List *list)
{
  struct List *p = list->next;

  if (p == NULL) {
    printf("empty list\n");
  } else {
    while (p != NULL) {
      printf(" %d", p->value);
      p = p->next;
    }
    printf("\n");
  }
}

void append_elem(struct List *list, int x)
{
  struct List *elem;
  struct List *tail;

  if ((elem = malloc(sizeof(struct List))) == NULL) {
    printf("malloc failed\n");
    exit(EXIT_FAILURE);
  }
  elem->value = x;
  elem->next = NULL;

  tail = list;
  while (tail->next != NULL)
    tail = tail->next;
  tail->next = elem;
}