下面是代码
#include <bits/stdc++.h>
using namespace std;
typedef struct teamLink
{
string tName;
int tScore;
int tNetGoal;
struct teamLink* nextTeam;
}*TeamLink;
void Insert(TeamLink &tL,TeamLink t)
{
if (tL == NULL)
tL = t;
else
{
TeamLink p = tL;
TeamLink pre = (TeamLink)malloc(sizeof(struct teamLink));
TeamLink tag = pre;
pre->nextTeam = p;
while(p->nextTeam != NULL && p->tScore > t->tScore)
{
p = p->nextTeam;
pre = pre->nextTeam;
}
if (p->nextTeam == NULL)
{
p->nextTeam = t;
free(tag);
return;
}
else
{
p = p->nextTeam;
while(p->nextTeam != NULL && p->tNetGoal > t->tNetGoal && p->tScore == t->tScore)
{
p = p->nextTeam;
pre = pre->nextTeam;
}
}
t->nextTeam = p;
pre->nextTeam = t;
free(tag);
}//else
return;
}
int main(int argc, char const *argv[])
{
int M,N;//参战队M 出线队N
cin>>M>>N;
cout<<M<<" "<<N<<endl;
TeamLink tL = NULL;
for (int i = 0; i < M; ++i)
{
cout<<i<<endl;
TeamLink t = (TeamLink)malloc(sizeof(struct teamLink));//应该是这行代码的问题
int win,plain,loss,goal,rgoal;
string name;
cin>>name>>win>>plain>>loss>>goal>>rgoal;
t->tName = name;
t->tScore = win*3 + plain;
t->tNetGoal = goal - rgoal;
t->nextTeam = NULL;
Insert(tL,t);
t = NULL;
cout<<tL->tName<<" "<<tL->tScore<<" "<<tL->tNetGoal<<endl;
}
TeamLink p = tL;
for (int i = 1; i <= N; ++i)
{
cout<<i<<"\t"<<p->tName<<"\t"<<p->tScore<<"\t"<<p->tNetGoal<<endl;
p=p->nextTeam;
}
return 0;
}
为什么第一次循环的时候可以malloc第二次反而不可以了呢?
样例:
4 2
德国 1 1 0 9 3
俄罗斯 1 0 0 2 1
威尔士 1 1 1 10 2
芬兰 0 1 0 3 3
输出:
1 威尔士 4 8
2 德国 4 6