此链表中的“结束时插入”操作有什么问题? 我编写了C++实现链表的代码。在我将insert-at-end函数添加到它之前,它工作得非常好。请看看出了什么事!如果没有InsertAttend函数,输出是正确的。添加该函数后,输出为110,这实际上是开始和结束时插入的输出 void List::insertatend(int num) { Node *new_node=new Node(num); if(listptr==NULL) listptr=new_node; else for(Node *temp=listptr; temp->next!=NULL; temp=temp->next) temp->next=new_node; }
浏览如何在前一个节点的末尾添加每个新节点的基本逻辑此链表中的“结束时插入”操作有什么问题? 我编写了C++实现链表的代码。在我将insert-at-end函数添加到它之前,它工作得非常好。请看看出了什么事!如果没有InsertAttend函数,输出是正确的。添加该函数后,输出为110,这实际上是开始和结束时插入的输出 void List::insertatend(int num) { Node *new_node=new Node(num); if(listptr==NULL) listptr=new_node; else for(Node *temp=listptr; temp->next!=NULL; temp=temp->next) temp->next=new_node; },c++,data-structures,linked-list,C++,Data Structures,Linked List,浏览如何在前一个节点的末尾添加每个新节点的基本逻辑 for(Node *temp=listptr; temp->next!=NULL; temp=temp->next) //it should be dummy loop temp->next=new_node;//In all old nodes next part will replace by new_node which is wrong 莫迪插入_结束函数为 void List::inser
for(Node *temp=listptr; temp->next!=NULL; temp=temp->next) //it should be dummy loop
temp->next=new_node;//In all old nodes next part will replace by new_node which is wrong
莫迪插入_结束函数为
void List::insertatend(int num)
{
Node *new_node=new Node(num);
if(listptr==NULL)
listptr=new_node;
else{
Node *temp=listptr;
for( temp ; temp->next!=NULL ; temp=temp->next); /** rotate dummy loop until temp is not reaching to last node **/
temp->next = new_node;// in last node next put the new node address
new_node->next = 0; // and new node nnext put the zero
}
}
问题在于:
for(Node *temp=listptr; temp->next!=NULL; temp=temp->next)
temp->next=new_node;
似乎您还没有了解代码如何工作的逻辑
首先需要迭代,直到temp->next为NULL,然后使用
temp->next=new_node;
实现该逻辑的代码是:
Node* temp = listptr;
for ( ; temp->next != NULL; temp = temp->next )
{
// Do nothing in the loop.
}
temp->next = new_node;
以下是更新后的函数:
void List::insertatend(int num)
{
Node* new_node = new Node(num);
if( listptr == NULL)
{
listptr = new_node;
}
else
{
Node* temp = listptr;
for ( ; temp->next != NULL; temp = temp->next )
{
}
temp->next = new_node;
}
}
它不是无限循环,因为它在next==NULL时停止。但是,如果OP使用调试器运行此代码,他们会在insertattend.new_node->next=0中发现明显的错误;“如果”和“否则”都需要发生。你不需要做出改变。请注意节点构造函数:Nodeint n{data=n;next=NULL;}。在user4581301Thanks处找到了它。感谢您的解释!我很明白!:您的代码无法使用new_node->next=NULL终止列表@斯塔克,Node的构造器负责这个。谢谢!我完全明白了!:@RSahu类列表应该保证它构建了一个正确的列表。它不应该依赖于类节点的构造函数。@stark,这是一个编码实践的问题。我喜欢OP确保节点的构造函数设置为NULL。