链接列表,在C++末尾插入

use*_*297 2 c++ linked-list

我正在编写一个简单的函数来插入C++上链表的末尾,但最后它只显示了第一个数据.我无法弄清楚什么是错的.这是功能:

void InsertAtEnd (node* &firstNode, string name){

        node* temp=firstNode;

        while(temp!=NULL) temp=temp->next;

            temp = new node;
        temp->data=name;
        temp->next=NULL;

        if(firstNode==NULL) firstNode=temp;

}
Run Code Online (Sandbox Code Playgroud)

Ant*_*ine 12

你写的是:

  • 如果firstNode为空,它替换为单个节点temp不具有下一个节点(和任何人的nexttemp)

  • 否则,如果firstNode不为null,则除了temp 节点被分配和泄漏之外没有任何反应.

以下是更正确的代码:

void insertAtEnd(node* &first, string name) {
    // create node
    node* temp = new node;
    temp->data = name;
    temp->next = NULL;

    if(!first) { // empty list becomes the new node
        first = temp;
        return;
    } else { // find last and link the new node
        node* last = first;
        while(last->next) last=last->next;
        last->next = temp;
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,我建议添加一个构造函数node:

struct node {
    std::string data;
    node* next;
    node(const std::string & val, node* n = 0) : data(val), next(n) {}
    node(node* n = 0) : next(n) {}
};
Run Code Online (Sandbox Code Playgroud)

这使您可以temp像这样创建节点:

node* temp = new node(name);
Run Code Online (Sandbox Code Playgroud)