【发布时间】:2014-12-15 21:44:52
【问题描述】:
当我使用“1”命令插入一个新的结构 A 时(所以我已经有一个或多个结构 A 链接到一个或多个结构 S),我失去了前一个结构 A 到它们的结构 S 的链接。 例如:
命令 1,然后是命令 3:2014 和命令 4
输出:
年份:2014
matricola:1
现在是命令 1,然后是命令 3:2015 和命令 4
输出:
年份:2015
matricola:2
年份:2014
没有S结构
我希望这个例子会有所帮助 代码如下:
#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;
}
}
这是我的第一篇文章,如有错误,我深表歉意。
【问题讨论】:
-
如果缩进正确,您的代码会更容易阅读。你有可以为你做的源格式化程序吗?
-
如果您有一个
if (cmd == 5) exit(1);并经过适当的清理,那就太好了。 -
不推荐使用
fflush(stdin),它打算与stdout一起使用。 -
单步调试代码时调试器会告诉你什么?
-
您应该清楚自己使用哪种语言进行编码。是 C 还是 C++?