【问题标题】:How to pass head from main to addNode function ? (LinkedList implementation via struct)如何将 head 从 main 传递到 addNode 函数? (通过结构实现 LinkedList)
【发布时间】:2019-05-22 20:49:42
【问题描述】:

在下面给出的代码中,我将 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;
    }
}

【问题讨论】:

    标签: c++ struct linked-list


    【解决方案1】:

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

    在函数范围内分配传递的头部(传递时复制)将影响函数范围。你可以做的是通过引用传递这个指针。所以你的代码会变成这样:

    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;
        }
    }
    

    【讨论】:

    • 你是绝对正确的。主要问题是,在按值传递head 指针时,它的值从未在addNode() 之外更改。如果这是一个 C 程序,解决方案是**head。相反,您选择了 &amp;*head,仅限 C++“引用指针”语法。此链接更详细地解释了该语法及其含义:Meaning of *& and **& in C++
    • @paulsm4 是的,它被标记为 C++,所以我猜这可能是要走的路,感谢您的链接,阅读愉快。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多