次のプログラムは、フォームの入力文字列を受け取り、ins "name_to_insert" birthdate
この情報を双方向リンク リストに挿入する必要があります。リストの内容は、各挿入後に要素数とともに表示されます。要素の数は正しく表示されていますが、名前と生年月日ではなく、2686707が n 回表示されています (n = リスト内の要素の数)。
印刷関数printList()に何か問題があると思われますが、何が原因かわかりませんでした。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "DLList.h"
typedef struct dataStructure
{
int birthday;
char *name;
} dataStructure;
int main()
{
ListT *l=createList();
char op[4], nameTemp[30], *name, s[50];
int date;
while (scanf("%[^\n]%*c", s)==1)
{
sscanf(s, "%s", op);
if (strcmp(op, "ins")==0)
{
sscanf(s, "%*s %[^0-9]%d", nameTemp, &date);
name=nameTemp+1; // Remove opening quotation mark
name[strlen(name)-2]='\0'; // Remove closing quotation mark
NodeT *p=createNode();
p->data=(dataStructure*)malloc(sizeof(dataStructure));
((dataStructure*)p->data)->birthday=date;
((dataStructure*)p->data)->name=name;
insertLastNode(l, p);
printf("List length: %d\n", l->length);
printList(l);
}
}
return 0;
}
void printList(ListT *l)
{
NodeT *p=l->first;
while (p)
{
printf("%d %s\n", (((dataStructure*)p->data)->birthday, (dataStructure*)p->data)->name);
p=p->next;
}
printf("--\n");
}
DLList.hの内容:
#include <stdio.h>
#include <stdlib.h>
typedef struct nodetype
{
struct nodetype *prev, *next;
void *data;
} NodeT;
typedef struct
{
int length;
NodeT *first, *last;
} ListT;
NodeT *createNode();
ListT *createList();
void insertLastNode(ListT *l, NodeT *p);
DLList.cの内容:
#include "DLList.h"
NodeT *createNode()
{
NodeT *p=(NodeT*)malloc(sizeof(NodeT));
p->next=p->prev=NULL;
return p;
}
ListT *createList()
{
ListT *l=(ListT*)malloc(sizeof(ListT));
l->first=l->last=NULL;
l->length=0;
return l;
}
void insertLastNode(ListT *l, NodeT *p)
{
if (l->first==NULL)
{
l->first=l->last=p;
p->prev=p->next=NULL;
l->length++;
}
else
{
p->prev=l->last;
p->next=NULL;
l->last->next=p;
l->last=p;
l->length++;
}
}