c++ - 为什么在链接列表中链接之前需要填充数据?

标签 c++ data-structures linked-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;
}

关于c++ - 为什么在链接列表中链接之前需要填充数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59657840/

相关文章:

c++ - Qt Creator 不打开终端

c++ - 让老鼠走出迷宫

python - 在python中将嵌套列表列表的元素从字符串转换为整数

c - 使用指针删除链表中的节点

c++ - 双向链表,tail 的问题

c++ - 使用 Makefile 和 GTest 对函数的 undefined reference

c++ - 唤醒 asio 截止时间计时器

javascript - JavaScript 有集合数据结构的实现吗?

c - 数组和链表哪个性能最好(就访问速度而言)

java - 创建 ListNode 的新实例