Skip to content

Instantly share code, notes, and snippets.

@xryuseix
Last active August 5, 2021 02:29
Show Gist options
  • Save xryuseix/195215aefdf48f3801a8a02000885e61 to your computer and use it in GitHub Desktop.
Save xryuseix/195215aefdf48f3801a8a02000885e61 to your computer and use it in GitHub Desktop.
Cで線型Listを作ります
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct __physcheck
{
char name[20];
int height;
double vision;
struct __physcheck *next;
} PhysCheck;
// headとtailは[head,tail]の閉区間
PhysCheck *head = NULL;
PhysCheck *tail = NULL;
void add(char *name, int height, double vision)
{
PhysCheck *x = malloc(1 * sizeof(PhysCheck));
strcpy(x->name, name);
x->height = height;
x->vision = vision;
x->next = NULL;
if (head == NULL)
{
x->next = NULL;
head = x;
tail = head;
}
else
{
tail->next = x;
tail = tail->next;
}
}
PhysCheck *find(char *name)
{
PhysCheck *crrPtr = head;
PhysCheck *befPtr = NULL;
while (crrPtr != NULL)
{
if (!strcmp(crrPtr->name, name))
{
return befPtr;
}
befPtr = crrPtr;
crrPtr = crrPtr->next;
}
return NULL;
}
void delete (char *name)
{
PhysCheck *befPtr = find(name);
if (befPtr == NULL)
{
// 先頭
PhysCheck *nextPtr = head->next;
free(head);
head = nextPtr;
}
else if (befPtr->next->next == NULL)
{
// 末尾
free(befPtr->next);
befPtr->next = NULL;
}
else
{
// 中間
PhysCheck *nextPtr = befPtr->next->next;
free(befPtr->next);
befPtr->next = nextPtr;
}
}
void print()
{
PhysCheck *crrPtr = head;
while (crrPtr != NULL)
{
printf("%s, %d, %f\n", crrPtr->name,
crrPtr->height, crrPtr->vision);
crrPtr = crrPtr->next;
}
}
int main(void)
{
add("AKASAKA Tadao", 162, 0.3);
add("KATOH Tomiaki", 173, 0.7);
add("NAGAHAMA Masaki", 168, 0.4);
add("HAMADA Tetsuaki", 174, 1.2);
print();
printf("\n");
delete ("NAGAHAMA Masaki"); // 中間
print();
printf("\n");
delete ("HAMADA Tetsuaki"); // 末尾
print();
printf("\n");
delete ("AKASAKA Tadao"); // 先頭
print();
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment