C++ 为什么这段代码卡在无限循环中?
为什么C++ 为什么这段代码卡在无限循环中?,c++,data-structures,linked-list,C++,Data Structures,Linked List,为什么head会变成某个随机值 // Simple insertion at the starting of link list #include<iostream> using namespace std; struct node{ int d; node *next; }; // creation of node node *head=new node; // is there any problem? void insert(int x) {
head
会变成某个随机值
// Simple insertion at the starting of link list
#include<iostream>
using namespace std;
struct node{
int d;
node *next;
}; // creation of node
node *head=new node; // is there any problem?
void insert(int x)
{
if (head==NULL) { // is there something wrong?
head->d=x;
haad->next=NULL;
} else {
node *t=new node;
t->d=x;
t->next=head;
head=t;
}
}
int main() {
insert(1); // function calling
insert(2); // function calling
insert(3); // function calling
while(head!=NULL) {
cout<<head->d<<" ";
head=head->next;
} // this is going on to infinity
return 0;
}
//在链接列表的开头简单插入
#包括
使用名称空间std;
结构节点{
int d;
节点*下一步;
}; // 创建节点
节点*头=新节点;//有什么问题吗?
空白插入(整数x)
{
如果(head==NULL){//有什么问题吗?
头部->d=x;
haad->next=NULL;
}否则{
node*t=新节点;
t->d=x;
t->next=头部;
水头=t;
}
}
int main(){
insert(1);//函数调用
插入(2);//函数调用
插入(3);//函数调用
while(head!=NULL){
couthead
将指向某个随机值,因为列表中的最后一个元素用next
指向一个随机值
最后一个元素是在此行中创建的第一个节点:
node *head=new node;
通过这样做,您在堆上为这个节点分配内存,但是,您没有为节点的字段设置任何值,包括next
。然后在循环中,当head
指向最后一个节点(首先分配的节点)head->next
不是NULL,因此循环继续
三个旁注:
使用head
本身迭代列表元素不是一个好主意,因为您将丢失指向列表头部的指针
head
可以全局声明,但通常你应该有一个很好的理由。在你的程序中,我会在main()
中定义它,并将它传递给需要它的函数
此代码:
if (head==NULL) { // is there something wrong?
head->d=x;
haad->next=NULL;
没有多大意义:它永远不会运行,如果它将-->分段错误(因为如果head
为NULL
,则无法引用其字段)
希望它有帮助。
你应该把编程语言添加到标签。改进的格式化、语法和标题。cOUT= = C++。我保证你应该避免使用<命名空间STD < /C> > <代码>。这是一个坏习惯,当你不期望它时,习惯于使用命名空间前缀(<代码> STD< /COD>故意短)。,或仅将所需的名称导入到最小的合理范围中。