为什么我们需要在链接列表链接之前填写数据?

Why we need to fill data before linking in link list?

本文关键字:链接 数据 列表 我们 为什么      更新时间:2023-10-16
#include<iostream>
using namespace std;
struct Data
{
string name;
int age;
string address;
string occupation;
struct Data *Next;
};
struct Data *Head=NULL,*Tail=NULL;
//here in my case. i am first linking Next & Head pointer before puting data in list.The code don't give any error but concept is not implemented properly.
void Add()
{
struct Data *temp;
temp = new Data;
if(Head==NULL)
{
Head=temp;
}else{
temp=Tail;
}
cout<< "Enter Your name :";
cin>> temp->name;
cout<< "Enter Your Age :";
cin>> temp->age;
cout<< "Enter Your Address:";
cin>> temp->address;
cout<< "Enter Your Occupation";
cin >>temp->occupation;
temp->Next = NULL;
Tail= (temp->Next) ;
}

请给我解释一下概念,为什么我们需要在连接之前放数据。 看看 void add(( 函数。阅读评论 在输入 1 上,它与数据插入一样正确,但经过一个周期后,下次在相同的输入上.是停止执行。

主要问题在这里:

temp=Tail;

在设置数据之前修改temp指向的内容。所以之后的所有东西都在修改Tail而不是temp.这也会导致内存泄漏。

还有其他问题,例如Tail始终nullptr,因为您需要在分配时分配它Head.此外,您最后没有正确链接临时。

void Add()
{
struct Data *temp = new Data;
if (!temp) return;
temp->Next = nullptr;
cout<< "Enter Your name :";
cin>> temp->name;
cout<< "Enter Your Age :";
cin>> temp->age;
cout<< "Enter Your Address:";
cin>> temp->address;
cout<< "Enter Your Occupation";
cin >>temp->occupation;
if (!Head) {
Head = Tail = temp;
}
else {
Tail->next = temp;
Tail = temp;
}
}

请注意,您也可以在链接后设置数据,只要您不修改temp指向的内容:

void Add()
{
struct Data *temp = new Data;
if (!temp) return;
temp->Next = nullptr;
if (!Head) {
Head = Tail = temp;
}
else {
Tail->next = temp;
Tail = temp;
}
cout<< "Enter Your name :";
cin>> temp->name;
cout<< "Enter Your Age :";
cin>> temp->age;
cout<< "Enter Your Address:";
cin>> temp->address;
cout<< "Enter Your Occupation";
cin >>temp->occupation;
}