我正在尝试创建一个链接列表,它创建正常但是当我尝试将新节点插入到已经非空的列表并显示它时,只存在新插入的节点。这是代码:
struct patient{
char name[NAME];
int ttime;
int atime;
int priority;
struct patient *next;
};
struct wr{
struct patient *fnode;
struct patient *lnode;
}*wr;
void wr_insert(struct patient *node){
if(wr->fnode == NULL){
wr->fnode = node;
wr->lnode = node;
}
else{
wr->lnode->next = node;
wr->lnode = node;
}
}
void display(){
struct patient *tmp = wr->fnode;
while(tmp != NULL){
printf("%s %d %d %d\n",tmp->name,tmp->ttime,tmp->atime,tmp->priority);
tmp = tmp->next;
}
}
void new_patient(char *line){
int i,check;
listsem = sem_open(lISTSEM, 0);
char *token;
token = strtok(line," ");
check = atoi(token);
if(check == 0){
struct patient *node = malloc(sizeof(struct patient));
strcpy(node->name,token);
node->ttime = atoi(strtok(NULL," "));
node->atime = atoi(strtok(NULL," "));
node->priority = atoi(strtok(NULL," "));
node->next = NULL;
sem_wait(listsem);
wr_insert(node);
sem_post(listsem);
}
else{
struct patient *group = malloc(sizeof(struct patient));
sprintf(group->name,"20171201-%d",groupnum);
group->ttime = atoi(strtok(NULL," "));
group->atime = atoi(strtok(NULL," "));
group->priority = atoi(strtok(NULL," "));
group->next = NULL;
groupnum++;
sem_wait(listsem);
wr_insert(group);
sem_post(listsem);
for(i=1;i<check;i++){
struct patient *node = malloc(sizeof(struct patient));
sprintf(node->name,"20171201-%d",groupnum);
node->ttime = group->ttime;
node->atime = group->atime;
node->priority = group->priority;
node->next = NULL;
groupnum++;
sem_wait(listsem);
wr_insert(node);
sem_post(listsem);
}
display();
}
get_patient();
}
因此,例如,如果我通过管道"3 10 20 30"
输入,它就会正确地显示我创建的3个节点。但是,如果我再次这样做,当它应该打印6个节点时,它只会再次打印3个,但是新的节点。
答案 0 :(得分:0)
这个结构定义/实例:
struct wr
{
struct patient *fnode;
struct patient *lnode;
} *wr;
不正确,因为根指针很好,但wr
的实例需要是结构的实例,而不是指向结构实例的指针。
推荐:
struct wr
{
struct patient *fnode;
struct patient *lnode;
} wr;
然后其余的代码需要将wr
视为结构的一个实例,而不是指向结构的指针所以这个:
void wr_insert(struct patient *node)
{
if(wr->fnode == NULL)
{
wr->fnode = node;
wr->lnode = node;
}
else
{
wr->lnode->next = node;
wr->lnode = node;
}
应该是:
void wr_insert(struct patient *node)
{
if(wr.fnode == NULL)
{
wr.fnode = node;
wr.lnode = node;
}
else
{
wr.lnode->next = node;
wr.lnode = node;
}