在此链接列表中的结束操作中插入有什么问题?

时间:2018-01-18 18:31:08

标签: c++ data-structures linked-list

我已编写此代码用于在c ++中实现Linked List。它完美地工作,直到我在它的最后功能添加插入。请看看有什么不对!没有insertatend函数,输出是正确的。添加该函数后,输出为1 10,实际上是在开始和结束输出时的插入。

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

2 个答案:

答案 0 :(得分:0)

完成如何在前一个节点末尾添加每个新节点的基本逻辑.Bug位于insertatend函数的下面两行,我在评论中提到了解释。

 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

Modiy Insert_end()的功能为

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

答案 1 :(得分:0)

问题在于:

for(Node *temp=listptr; temp->next!=NULL; temp=temp->next)
        temp->next=new_node;

看起来你还没有完成代码工作原理的逻辑。

首先需要进行迭代,直到temp->nextNULL,然后再使用

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