#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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句