为什么我们需要在链接列表链接之前填写数据?
Why we need to fill data before linking in link list?
#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;
}
相关文章:
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 指向(数据)成员的指针作为非类型模板参数,例如具有自动存储持续时间/无链接
- 为什么我们需要在链接列表链接之前填写数据?
- 使用 trie 数据结构链接不同类型的信息
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 将多个效果与 libSox 链接并读取输出数据的正确方法
- 链接列表(C )中(字符串)数据的用户输入
- 是否可以将同一组源数据与不同的表模型链接起来?
- 实现双链接列表,其中数据存储在堆上
- 如何使用模板在数据结构中链接节点对象
- C、链接数据结构和双指针行为
- 将数据从文件读取到链接列表中,并在链接列表中搜索元素
- 计算列表中与线性链接列表中最后一个节点具有相同数据的节点的数量
- Qt命令行编译在链接器阶段失败,出现垃圾NXCOMPAT数据
- 为什么添加静态数据成员会导致链接器失败
- 访问注册表数据以设置链接器和包含路径
- C 链接列表 - 带有前哨的文件中读取数据
- 为什么我的链接数据类型复制构造函数不起作用?
- 图实现,使用邻接矩阵,在链接中带有自定义数据
- 在链接列表中添加数据