【问题标题】:Why am I not getting any output, for my code on insertion in linked list? [closed]为什么我的代码在链表中插入时没有得到任何输出? [关闭]
【发布时间】: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


【解决方案1】:

请帮我调试我的代码

好的,让我们试试试运行

假设您的列表是空的并且您正在插入您的第一个项目。所以root 等于NULL,我们称之为insert

1) 第一件事

struct node *temp=new(struct node);

您分配一个新节点,并将temp 设置为等于它,到目前为止一切顺利。

2) 下一件事

if(root==NULL)

如前言所述,这是真的,所以我们输入 if 语句

3) 下一件事

temp->data=data;
temp->next=NULL;

if 主体中的这些语句被执行并初始化新分配的对象。目前尚不清楚为什么您只想在root == NULL 时执行此操作,我认为您希望始终初始化新分配的节点。但无论如何,到目前为止没有错误。

4) 下一件事

root->next=temp;

现在这是错误。问问自己,此时root 的价值是多少?当我们开始时它是NULL,从那以后有什么改变吗?答案当然是否定的,因此您取消引用 NULL 指针。这就解释了错误。

您需要能够查看您编写的代码并了解它的实际作用。像我上面那样试运行您的代码的能力是一项非常有价值的技能。

不幸的是,您的代码确实不是很接近正确。所以我认为最好的办法是查看一些工作代码,看看它是如何运行的,然后重新开始。

【讨论】:

  • 我没有看到这个结构节点 *temp=new(struct node);它无处不在
  • @Oblivion 我打算评论可疑的语法,但我认为最好集中在要点上。对于 OP,该行最好写为 node* temp = new node;
  • @john 我想使用 if(root==NULL) 创建一个初始节点;我尝试制作一个头和尾节点,它可以工作。如果(头== NULL){头=临时;尾巴=温度; } else {tail->next = temp;tail = tail->next;非常感谢:)
  • @john OP 使用了 C 风格。我发现了这个:stackoverflow.com/q/39838629/10933809
猜你喜欢
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多