【发布时间】:2019-08-17 14:48:35
【问题描述】:
我正在尝试通过在末尾插入节点来创建单链表,尽管没有错误,但我无法打印我的链表。请帮我调试我的代码。
我在 codechef 上尝试了在线编译器,它显示 SIGSEGV 运行时错误。这是什么意思?
struct node
{
int data;
struct node *next;
};
void insert(struct node *root,int data)
{
struct node *temp=new(struct node);
if(root==NULL)
{
temp->data=data;
temp->next=NULL;
}
root->next=temp;
temp->data=data;
temp->next=NULL;
}
void print(struct node *root)
{
struct node *temp;
temp=root;
while(temp!=NULL)
{
cout<<temp->data;
temp=temp->next;
}
}
int main()
{
struct node *root=NULL;
insert(root,1);
insert(root,2);
insert(root,3);
insert(root,4);
print(root);
return 0;
}
【问题讨论】:
-
“请帮我调试我的代码。”不! Stack Overflow 不是免费的在线调试服务。即使在网上也有一些方法可以帮助自己,例如:onlinegdb.com。
-
这意味着你的代码调用了未定义的行为。您的
insert在多个地方损坏。 -
"它显示 SIGSEGV 运行时错误。这是什么意思?" - 分段错误 (SIGSEGV) 意味着您的程序试图在其分配的地址空间之外读取或写入内存。这是一个致命错误,内核(正确地)因违规而终止了程序。
-
请不要在新代码中使用
NULL。使用nullptr。 -
您可能需要花一点时间调查ClangFormat...
标签: c++ linked-list singly-linked-list insertion