|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct list {
int key; /* キー */
char name[20]; /* 名前 */
struct list *next; /* 次のデータへのポインタ */
} list_t;
list_t *add_list(int key, char *name, list_t *head);
void show_list(list_t *p);
void free_list(list_t *p);
int main()
{
struct list *head; /* 先頭ポインタ */
char name[20];
char lines[80];
int key = 0, i = 0;
head = NULL; /* 先頭ポインタにNULLを設定 */
printf("キーと名前(MAX:19文字)を入力(終了:データを4つ入力したら)n");
while (i < 4) {
fgets(lines, 80, stdin);
sscanf(lines, "%d %s", &key, name);
/* リストにデータを登録 */
head = add_list(key, name, head);
i++;
}
/* リストの表示 */
show_list(head);
/* リストの開放 */
free_list(head);
return 0;
}
list_t *add_list(int key, char *name, list_t *head)
{
list_t *p, *new_p;
/* 記憶領域の確保 */
new_p = (list_t *)malloc(sizeof(list_t));
/* リストにデータを登録 */
new_p->key = key;
strcpy(new_p->name, name);
if (head == NULL || key > head->key) {
/* ポインタのつなぎ換え */
new_p->next = head;
return new_p;
}
/* キーのサーチ */
for ( p = head; p->next != NULL; p = p->next )
if ( key > p->next->key ) break;
/* ポインタのつなぎ換え */
new_p->next = p->next;
p->next = new_p;
return head;
}
void show_list(list_t *p)
{
while (p != NULL) { /* 次ポインタがNULLまで処理 */
printf("%3d %sn", p->key, p->name);
p = p->next;
}
}
/*** リストの開放 ***/
void free_list(list_t *p)
{
list_t *p2;
while (p != NULL) { /* 次ポインタがNULLまで処理 */
p2 = p->next;
free(p);
p = p2;
}
}
上のプログラムを双方向リストを用い、追加、挿入、削除できるようにしたらどうなりますか?
|