Linked List, insert at the end C++(链表,在末尾插入 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为空,它被替换为单个节点temp没有下一个节点(没有人的next是temp)
if
firstNodeis null, it's replaced with the single nodetempwhich has no next node (and nobody'snextistemp)
否则,如果 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++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:链表,在末尾插入 C++
				
        
 
            
        基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 这个宏可以转换成函数吗? 2022-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				