当我使用“ 1”命令插入新的结构A(因此我已经有一个或多个结构A链接到一个或多个结构S)时,我失去了先前结构A到其结构S的链接。
例如:
命令1,然后命令3:2014和命令4
输出:
年:2014
基质胶:1
现在命令1,然后命令3:2015和命令4
输出:
年:2015
基质:2
年:2014
没有结构
我希望这个例子会有所帮助
这是代码:
#include <stdio.h>
#include <stdlib.h>
struct S
{
int matr;
struct S* next;
};
struct A
{
int year;
struct A *nextA;
struct S *nextS;
};
int years = 2013;
int matricola=0;
void insA(struct A**T);
void printA(struct A*T);
void insS(struct A **T);
void printS(struct A *T);
int main()
{
struct A *T=NULL;
int cmd,sc=0;
while(1)
{
printf("\n command:");
sc=scanf("%d",&cmd);
while(sc==0)
{
printf("\nerror:");
fflush(stdin);
sc=scanf("%d",&cmd);
}
if(cmd==1)
{
insA(&T);
}
if(cmd==2)
{
printA(T);
}
if(cmd==3)
{
insS(&T);
}
if(cmd==4)
{
printS(T);
}
}
return 0;
}
void insA(struct A**T)
{
struct A *new_p=(struct A*)malloc(sizeof(struct A));
if(new_p==NULL)
{
printf("Errore");
exit(0);
}
years++;
new_p->nextA=NULL;
new_p->nextS=NULL;
if((*T)==NULL)
{
(*T)=new_p;
}
else
{
new_p->nextA=(*T);
(*T)=new_p;
}
new_p->year=years;
}
void printA(struct A *T)
{
struct A *tmp=T;
while(tmp!=NULL)
{
printf("\n%d",tmp->year);
tmp=tmp->nextA;
}
return;
}
void insS(struct A **T)
{
int search,sc=0;
struct S* new_p=(struct S*)malloc(sizeof(struct S));
if(new_p==NULL)
{
printf("error");
exit(0);
}
new_p->next=NULL;
printf("\nyear in which to insert:");
sc=scanf("%4d",&search);
while(sc==0 || search > years || search <= 2013)
{
printf("\nerror:");
fflush(stdin);
sc=scanf("%4d",&search);
}
struct A*tmp=*T;
while(tmp!=NULL)
{
if(tmp->year==search)
{
matricola++;
if(tmp->nextS==NULL)
{
tmp->nextS=new_p;
}
else
{
new_p->next=tmp->nextS;
tmp->nextS=new_p;
}
}
tmp=tmp->nextA;
}
new_p->matr=matricola;
return;
}
void printS(struct A *T)
{
struct A *tmp=T;
struct S *s=tmp->nextS;
while(tmp!=NULL)
{
printf("\nyear:%d",tmp->year);
if(s==NULL)
{
printf("\nno S struct");
return;
}
else
{
while(s!=NULL)
{
printf("\nmatricola:%d",s->matr);
s=s->next;
}
}
tmp=tmp->nextA;
}
}
这是我的第一篇文章,对于任何错误我深表歉意。
最佳答案
在努力理解您要做什么之后,我找出了您的问题,您必须更改printS函数。
void printS(struct A *T) {
struct A *tmp=T;
truct S *s = tmp->nextS;
while(tmp != NULL) {
printf("\nyear:%d", tmp->year);
if(s == NULL) {
printf("\nno S struct");
return ;
} else {
while(s != NULL) {
printf("\nmatricola:%d",s->matr);
s = s->next;
}
}
tmp = tmp->nextA;
}
}
像这样。
void printS(struct A *T) {
struct A *tmp=T;
while(tmp != NULL) {
struct S *s = tmp->nextS;
printf("\nyear:%d", tmp->year);
if(s == NULL) {
printf("\nno S struct");
return ;
} else {
while(s != NULL) {
printf("\nmatricola:%d",s->matr);
s = s->next;
}
}
tmp = tmp->nextA;
}
}
因为
struct S *s = tmp->nextS;
必须更新为您所在的实际结构A,所以它必须位于while循环中,如果将struct S *s = tmp->nextS;
保留在while循环之外,则将尝试打印结构S的列表,从第一个结构A开始,而不是结构S的整个列表都从每个结构A开始。注意:正如我所说,请尽量避免使用
fflush(stdin);
,因为如果参数未指向输出流,则行为是不确定的。