要素としてある場合、数値はリストに代入せず、またリストにあるその数値も削除する。
要素としてない時、リストに代入する。 と言うプログラムを書きたいのだが、
リストの動きがわからず、申し訳ないのですがご教授お願いします。
求めたい実行結果
input = 3
[ 3 ]
input = 5
[ 5 3 ]
input = 3
[ 5 ]
input = 4
[ 4 5 ]
input = 4
[ 5 ]
input = ^d
自分のプログラム実行結果
input = 3
[ 3 ]
input = 5
[ 5 3 ]
input = 3
[ 5 ]
input = 4
[ 4 5 ]
input = 4
Error: p->next = NULL
以下プログラム
#include <stdio.h>
#include <stdlib.h>
typedef struct list_node_s
{
int val;
struct list_node_s *next;
} list_node_t;
static list_node_t* insert_node(list_node_t *p, int val);
static void remove_node(list_node_t *p);
void list_print(list_node_t *list);
list_node_t* create_node(int val);
list_node_t* list_insert(list_node_t *list, int val);
list_node_t* list_find(list_node_t *list, int val);
list_node_t* list_insert_uniq(list_node_t *list, int val);
list_node_t* list_insert_delete_dup(list_node_t *list, int val);
int main(void)
{
list_node_t *head_p = create_node(0); /* ヘッダ (ダミー) */
for (;;) {
int val;
fprintf(stderr, "input = ");
if (scanf("%d", &val)==EOF) { break; }
list_insert_delete_dup(head_p,val);
list_print(head_p);
}
list_delete(head_p);
free(head_p);
return 0;
}
/* 値 val を保持する新しい節点を作成し, その節点へのポインタを返す */
list_node_t* create_node(int val)
{
list_node_t *new_node;
new_node = (list_node_t*) malloc(sizeof(list_node_t));
if (new_node == NULL) {
fprintf(stderr, "節点の割当てに失敗しました\n");
exit(1);
}
new_node->val = val;
new_node->next = NULL;
return new_node;
}
/* n の指す節点の直後に, 値 val を保持する新しい節点を挿入し,
その節点へのポインタを返す */
static list_node_t* insert_node(list_node_t *n, int val)
{
list_node_t *new_node = create_node(val);
new_node->next = n->next;
n->next = new_node;
return new_node;
}
/* リストの内容を表示する */
void list_print(list_node_t *head_p)
{
list_node_t *p;
printf("[ ");
for( p = head_p->next; p != NULL; p = p->next ){
printf( " %d ", p->val );
}
printf(" ]\n");
}
/* p の指す節点の *直後* の節点を削除 */
static void remove_node(list_node_t *p)
{
list_node_t *old = p->next;
if (old==NULL) {
fprintf(stderr, "Error: p->next = NULL\n");
exit(1);
}
p->next = old->next;
free(old);
old = NULL;
}
/* ヘッダが head_p のリストの先頭に値 val (の節点) を挿入する */
list_node_t* list_insert(list_node_t* head_p, int val)
{
list_node_t* p = insert_node(head_p,val);
return p;
}
/* リスト中に値が val の節点を探す
見つかればその節点のポインタを, なければ NULL を返す */
list_node_t* list_find(list_node_t *head_p, int val)
{
list_node_t *p;
for( p = head_p->next; p != NULL; p = p->next ){
if(p->val == val){
return p;
}
}
return NULL;
}
/* 以下を編集したい */
list_node_t* list_insert_delete_dup(list_node_t* head_p, int val)
{
list_node_t *p;
list_node_t *q = NULL;
p = list_find(head_p, val);
if( p == NULL ){
q = list_insert(head_p,val);
}
else{
remove_node(p+1);
return NULL;
}
return q;
}