链表,在C ++末尾插入 [英] Linked List, insert at the end C++

查看:49
本文介绍了链表,在C ++末尾插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写一个简单的函数,将其插入C ++链表的末尾,但最终它仅显示第一个数据.我不知道怎么了.这是功能:

I was writing a simple function to insert at the end of a linked list on C++, but finally it only shows the first data. I can't figure what's wrong. This is the function:

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;

}

推荐答案

您写的是:

  • 如果 firstNode 为null,则将其替换为单个节点 temp 没有下一个节点(没有人的 nexttemp)

  • if firstNode is null, it's replaced with the single node temp which has no next node (and nobody's next is temp)

否则,如果 firstNode 不为null,则除了 temp 节点已分配并泄漏.

Else, if firstNode is not null, nothing happens, except that the temp node is allocated and leaked.

以下是更正确的代码:

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

此外,我建议将构造函数添加到 node :

Also, I would suggest adding a constructor to 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) {}
};

您可以通过以下方式创建 temp 节点:

Which enables you to create the temp node like this:

node* temp = new node(name);

这篇关于链表,在C ++末尾插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆