Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 单链表插入问题_C++_Linked List - Fatal编程技术网

C++ 单链表插入问题

C++ 单链表插入问题,c++,linked-list,C++,Linked List,我试图在链表的末尾插入元素,但如果我对while循环中的中断进行注释,它将进入一个连续循环,我不知道为什么 代码: head=NULL; 节点*温度=头部; 对于(int i=0;ia=i; t1->next=NULL; 水头=t1; } 其他的 { 温度=水头; while(temp!=NULL) { 如果(临时->下一步==NULL) { t1->a=i; t1->next=NULL; 温度->下一步=t1; //中断; } 温度=温度->下一步; } } } 温度=水头; while(te

我试图在链表的末尾插入元素,但如果我对while循环中的中断进行注释,它将进入一个连续循环,我不知道为什么

代码:

head=NULL;
节点*温度=头部;
对于(int i=0;ia=i;
t1->next=NULL;
水头=t1;
}
其他的
{
温度=水头;
while(temp!=NULL)
{
如果(临时->下一步==NULL)
{
t1->a=i;
t1->next=NULL;
温度->下一步=t1;
//中断;
}
温度=温度->下一步;
}
}
}
温度=水头;
while(temp!=NULL)
{

cout您的while循环正在尝试一次又一次地遍历您刚刚添加的新节点。在这里插入操作后中断循环是正确的,否则while循环可能会无限期地循环。

您的while
循环将永远运行,而不会中断
循环,因为
temp
从未设置为NULL以停止循环。当
while
循环到达列表中的最后一个节点时,它会将新节点追加到末尾,然后将
temp
设置到该节点。因此,下一次循环迭代会看到该节点,一次又一次无休止地追加

因此,当到达最后一个节点时,需要
中断
while
循环:

for(int i=0;i<5;i++)
{
node*t1=新节点;
t1->a=i;
t1->next=NULL;
if(head==NULL)
{
水头=t1;
}
其他的
{
节点*温度=头部;
while(temp!=NULL)
{
如果(临时->下一步==NULL)
{
温度->下一步=t1;
打破
}
温度=温度->下一步;
}
}
}
在这种情况下,
while
循环可以简化为根本不需要
break

for(int i=0;i<5;i++)
{
node*t1=新节点;
t1->a=i;
t1->next=NULL;
if(head==NULL)
{
水头=t1;
}
其他的
{
节点*温度=头部;
while(临时->下一步!=NULL)
{
温度=温度->下一步;
}
温度->下一步=t1;
}
}

这就是说,整个代码可以进一步大大简化,不必在外部
for
循环的每次迭代中重复整个列表,也不必使用
if..else
来决定是否设置
头部

节点**温度=&head;
while(*temp!=NULL)
{
温度=&(*温度)->下一步;
}
对于(int i=0;i<5;i++)
{
node*t1=新节点;
t1->a=i;
t1->next=NULL;
*温度=t1;
温度=&(t1->next);
}
head=NULL;
node *temp=head;

for(int i=0;i<5;i++)
{
    //temp=head;
    node* t1=new node;
        
    if(head==NULL)
    {
        t1->a=i;
        t1->next=NULL;
        head=t1;
    }
    else
    {
        temp=head;
        while(temp!=NULL)
        {
            if(temp->next==NULL)
            {
                t1->a=i;
                t1->next=NULL;
                temp->next=t1;
                //break;
            }
            temp=temp->next;
        }
    }
}

temp=head;
while(temp!=NULL)
{
    cout<<temp->a<<endl;
    temp=temp->next;
}