要求是通过循环语句生成结点,创建一个单链表,保存1-30间的所有30个整数,并且输出。
😭😭输出结果1的循环是哪一步出了问题啊
源代码如下
#include
#include
using namespace std;
struct node{
int data;
struct nodenext;
};
int main()
{
struct nodeq=(struct node*)malloc(sizeof(struct node));
struct node*t=q;
for(int i=1;i<=30;i++){
struct node*s=(struct node*)malloc(sizeof(struct node));
s->data=i;
t->next=s;
t=s;
}
t->next=NULL;
cout<<endl;
for(t=q->next;t;t->next){
cout<data<<" ";
}
return 0;
}
for(t = q->next;t;t=t->next)
...
最后应该是t=t->next,这样t才不断指向链表的下一个节点。
t->next是不会改变t的值的。所以t没有改变,导致死循环了。
把 20 行的 循环的 t 变量,改为另一个名字, 不要重复使用 t
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!