c++ - 如何将 head 从 main 传递到 addNode 函数? (通过结构实现 LinkedList)

标签 c++ struct linked-list

在下面给出的代码中,我将 head-pointer 从 main 函数传递给 addNode 函数,这样我就保留了 head-pointer 的位置(也将它传递给其他 linkedList 相关函数以执行其他操作)但是下面的代码不起作用正如预期的那样,每次我调用函数 addNode 时,我都会得到 Head node Created,我是否没有正确地将指针传递给 addNode?我如何实现将头指针保留到列表并将其从 main() 发送到 addNode 函数的目标?

using namespace std;

struct stud {
    string stud_name;
    string stud_roll:
    stud *next_node;
};

void addNode(stud* head);


int main()
{   stud *head = nullptr;
    addNode(head);
    addNode(head);
    addNode(head);
    addNode(head);
    addNode(head);
}

void addNode(stud* head)
{

    stud *new_node = new stud;
    new_node->next_node = NULL;

    if (head == NULL)
    {
        head = new_node;
        cout << "Head node Created" << endl;
    }
    else
    {
        stud *temp_head = NULL;
        temp_head = head;

        while (temp_head->next_node != NULL)
        {
            temp_head = temp_head->next_node;
            cout << "Moving temp pointer" << endl;
        }
        temp_head->next_node = new_node;
        cout << "Body node created" << endl;
    }
}

最佳答案

您在这里所做的是,传递一个指向函数的指针并在函数中(本地)分配它,并且您希望该局部指针可以在函数范围之外访问和重用。你能看出问题所在吗?

在函数作用域中分配传递的头部(传递时复制)会影响函数作用域。您可以做的是通过引用传递此指针。所以你的代码会像这样改变:

struct stud {
    string stud_name;
    string stud_roll;
    stud *next_node;
};

void addNode(stud *&head);

int main()
{
    stud *head = nullptr;
    addNode(head);
    addNode(head);
    addNode(head);
    addNode(head);
    addNode(head);
}

void addNode(stud *&head)
{

    stud *new_node = new stud;
    new_node->next_node = NULL;

    if (head == NULL)
    {
        head = new_node;
        cout << "Head node Created" << endl;
    }
    else
    {
        stud *temp_head = NULL;
        temp_head = head;

        while (temp_head->next_node != NULL)
        {
            temp_head = temp_head->next_node;
            cout << "Moving temp pointer" << endl;
        }
        temp_head->next_node = new_node;
        cout << "Body node created" << endl;
    }
}

关于c++ - 如何将 head 从 main 传递到 addNode 函数? (通过结构实现 LinkedList),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53900740/

相关文章:

c++ - 如何使用成对的 STL 二进制搜索操作?

c++ - AVX 循环矢量化中的奇怪错误

pointers - Rust 中的指针转换是否与 C++ 中的 reinterpret_cast 具有相同的行为?

分配复合结构时 C 程序崩溃

json - 当结构未知时遍历 JSON 响应

Python:如何完全删除链表?

c - 我的 pop 函数(队列)C 做错了什么

c++ - 我的代码的某些部分没有运行

c++ - 反向链表的一部分

c++ - C++ 中函数的关键字?