链接覆盖的数据

chained overwritten data

本文关键字:数据 覆盖 链接      更新时间:2023-10-16

我用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<<"nnNew dataset created.nn";
        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;
}

当您正在查找链接列表的末尾时

if (pRun->pnext !=  NULL)
{
    pRun        =   pRun->pnext;
}

您希望使用while而不是if来处理列表中已有几个节点的情况。

打印时已经这样做了,但插入时没有。