【发布时间】:2016-01-29 06:09:08
【问题描述】:
我用 C++ 编写了这个简单的链表。但是有一个奇怪的问题让
让我一头雾水。在我的程序中,用户应该能够输入任意数量的姓名和年龄,并且他们都应该相互链接。
但是,如果我输入 A 和 1、B 和 2、C 和 3,然后输入 D 和 4,那么 C and 3 将被 D and 4 覆盖。有人可以解释为什么会这样吗?
代码:
#include<iostream>
#include<string>
using namespace std;
struct T_Schueler
{
string Name;
string Age;
T_Schueler *pnext;
};
T_Schueler *pStart = NULL;
int main()
{
string name, age;
while(true)
{
system("cls");
cout<<"Please enter name: ";
cin>> name;
cout<<"Please enter age: ";
cin>> age;
T_Schueler *pAllok, *pRun, *pLoesch;
pAllok = new(T_Schueler);
pAllok->pnext = NULL;
cout<<"\n\nNew dataset created.\n\n";
if(pStart == NULL)
{
pStart = pAllok;
pStart->Name = name;
pStart->Age = age;
}
else
{
pRun = pStart;
if (pRun->pnext != NULL)
{
pRun = pRun->pnext;
}
pRun->pnext = pAllok;
pRun = pRun->pnext;
pRun->Name = name;
pRun->Age = age;
}
//OUtput
pRun = pStart;
cout<<"Names: "<<endl;
while(pRun != NULL)
{
cout<< pRun->Name << " -> ";
pRun = pRun->pnext;
}
pRun = pStart;
cout<<"\nAges: "<<endl;
while(pRun != NULL)
{
cout<< pRun->Age << " -> ";
pRun = pRun->pnext;
}
cout<<endl;
system("PAUSE");
}
cin.get();cin.get();
return 0;
}
【问题讨论】: