c++ - 在hackerrank平台上的列表中插入节点时出现段错误

标签 c++ linked-list

我正在hackerrank平台上运行测试。我必须在列表的末尾插入给定的数据。
类表示...

class SinglyLinkedListNode {
    public:
        int data;
        SinglyLinkedListNode *next;

        SinglyLinkedListNode(int node_data) {
            this->data = node_data;
            this->next = nullptr;
        }
};

它已经嵌入在代码编辑器中。我不能改变
这是显式声明的函数,该函数不与任何类关联。
// function to insert node at the tail of the list. 
SinglyLinkedListNode * insertNodeAtTail(SinglyLinkedListNode * head, int data) {

  SinglyLinkedListNode * nn = new SinglyLinkedListNode(data);
  // node to traverse the list
  SinglyLinkedListNode * temp = head;

  if (!head)
  {
    head = nn;
    return head;
  } 
  else
  {
    while (temp)
    {
      temp = temp - > next;
    }
    temp - > next = nn;
  }

  return head;
}

我收到 Segmentation Fault。
错误(stderr)消息:
Reading symbols from Solution...done.
[New LWP 113196]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./Solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  insertNodeAtTail (data=302, head=<optimized out>) at Solution.cpp:70
70         temp->next=nn;
To enable execution of this file add
    add-auto-load-safe-path /usr/local/lib64/libstdc++.so.6.0.25-gdb.py
line to your configuration file "//.gdbinit".
To completely disable this security protection add
    set auto-load safe-path /
line to your configuration file "//.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual.  E.g., run from the shell:
    info "(gdb)Auto-loading safe path"

如我所见,我没有取消引用任何未分配的内存。
有什么错误?

最佳答案

您应该始终首先使用调试器。在这段代码中,您正在观看一个插入它的下一个指针的指针。

 while(temp->next) {
    temp = temp->next;
  }

  temp->next = nn;

这是正确的代码。

关于c++ - 在hackerrank平台上的列表中插入节点时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60784612/

相关文章:

c++ - 我可以依赖模板类型吗?

c++ - 交线多边形 boost 几何体

c - 将字符串与链表数据元素进行比较时,strcmp 不会返回 0

c - 链表和指针指向正确吗?

java - 测量 ArrayList 和 LinkedList 上的插入操作所花费的时间

c++ - 正确处理静态 HTREEITEM 的清理

c++ - -l : option via Eclipse

c - 当我更改字符数组时链表更改

algorithm - 排序链表最快的算法是什么?

C++ 第二个计数器