我需要一些关于此链接列表练习的帮助。函数listTasks()
应该显示struct task
的所有实例。当我第一次执行该函数时,它按预期工作,但是当我再次执行它时,它不会显示来自struct action
的内容,即使我依次执行它们。
typedef struct action
{
char parametre[100];
char command[100];
struct action* next;
struct action* previous;
}* Action;
typedef struct task
{
char name[100];
struct task* next;
struct task* previous;
Action action;
}* Task;
void listTasks(Task tar, char* name)
{
if(tar==NULL) printf("There is no task with the name: %s\n",name);
else
{
while(tar!=NULL&&strcmp(tar->name,name)!=0)
{
tar = tar->next;
}
if(tar!=NULL && strcmp(tar->name,name)==0)
{
printf("Task: %s\n",tar->name);
if(tar->action==NULL) printf("->It doesnt have any action.\n");
else if(tar->action!=NULL)
{
while(tar->action!=NULL)
{
printf("->Command: %s\n->->Parametre: %s\n",tar->action->command,tar->action->parametre);
tar->action = tar->action->next;
}
}
}
else printf("There is no task with the name: %s\n",name);
}
}
void main()
{
task a = NULL;
listTasks(a,"random name");
}
答案 0 :(得分:4)
你的问题在这里:
while(tar->action!=NULL)
{
printf("->Command: %s\n->->Parametre: %s\n",tar->action->command,tar->action->parametre);
tar->action = tar->action->next;
}
你正在破坏性地改变tar->action
。是的,它第一次有效,但在此之后,tar->action
将是NULL
,这就是数据“消失”的原因。
如果您不想销毁操作列表,则必须使用临时变量遍历它。有点像:
struct action *action = tar->action;
while(action!=NULL)
{
printf("->Command: %s\n->->Parametre: %s\n",action->command,action->parametre);
action = action->next;
}