我用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;
}
答案 0 :(得分:2)
当您在寻找链表的末尾时
if (pRun->pnext != NULL)
{
pRun = pRun->pnext;
}
您希望使用while
代替if
来处理列表中已有多个节点的情况。
您在打印时已经这样做了,但在插入时却没有。