为什么这个添加项功能的无限循环? [英] Why infinite loop for this add item function?

查看:89
本文介绍了为什么这个添加项功能的无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最后为链接列表添加了一个项目功能,我有两个问题

1)我怎样才能将头节点作为参考指针传递?

2)当我在函数结束时删除* temp时,为什么函数会进行无限循环。



I made a add item function for link list at the end , I have two questions
1) how can i get away with passing head node as a reference pointer?
2) why does function go on infinite loop when i am deleting *temp at the end of function.

void addItemEnd(int num, Node *&head)
{
    Node *temp =new Node;
    temp->data=num;
    temp->next=NULL;

    Node *temp1=head;
    if(head==NULL)
    {
        cout << "List is currently Empty, 1st element added"<<endl;
        head=temp;
    }
    else
    {
        while(temp1->next!=NULL)
            temp1=temp1->next;
        temp1->next=temp;
        //head=temp1;

    }

    delete temp; // adding of this making infinite loop else it work fine

}





[edit]已添加代码块 - OriginalGriff [/ edit]



[edit]Code block added - OriginalGriff[/edit]

推荐答案

考虑一下:如果您正在创建一个新节点并将其添加到列表中,然后将其删除,那么下次您尝试创建新节点时,您将获得相同的内存 - 它的大小合适,并且它是免费的。并且它已经在列表中......所以当你尝试按照列表进行操作时,第一项已经是一个节点(已删除的节点),你将它的下一个地址设置为新节点(占用相同的内存),所以它是一个小小的单节点循环。所以你的while循环只是跟随它自己的下一个链接再次尝试...



不要删除你刚刚创建的节点!你应该只在你完成它时删除它 - 这是当你从列表中删除它并丢弃它,或者你丢弃整个列表。



试试看在调试器中它,你应该看到我的意思。
Think about it: If you are creating a new node and adding it into your list, then deleting it, then the next time you try to create a new node, you will get the same memory - it's the right size, and it's free. And it's already in the list...so when you try to follow the list through, the first item is already a node (the deleted one) and you set it's next address to the new node (which occupies the same memory) so it is a little tiny one-node loop. So your while loop just follows its next link to itself and tried again...

Don't delete the node you just created! You should only delete it when you have finished with it - which is when you remove it from the list and discard it, or you discard the whole list.

Try looking at it in the debugger and you should see what I mean.


这篇关于为什么这个添加项功能的无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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