尝试将节点添加到 C++ 中链表的末尾时出现分段错误(核心转储)错误

I'm getting a segmentation fault (core dumped) error when trying to add an Node to the end of a Linked List in c++

所以我创建了一个新的链表,但在链表的末尾插入一个新节点时遇到了问题。我尝试了遍历列表的不同迭代,但我认为问题出在我尝试插入节点的最后。

#include <iostream>
using namespace std;
//Make a basic linked list and understand how it works -- displaying -- insert at end 

class Node {
public: 
    string m_name;
    Node *m_next;
};

class LinkedList {
public:
    Node *m_head;
    int m_size;
    LinkedList() { //constructor
        m_head = nullptr;
        m_size = 0;
    }
    void InsertAtEnd(Node *ptr) { //we must traverse to the end
        Node *temp = m_head;
        while (temp != nullptr) {
            temp = temp->m_next;
        }
        temp->m_next = ptr->m_next;
    }
    void Display() {
        Node *temp = m_head;
        if (temp == nullptr) {
            cout << "The linked list is empty!" << endl;
        }
        else {
            while (temp->m_next != nullptr) {
                cout << temp->m_name << " ";
                temp = temp->m_next;
            }
        }
    }

};

int main() {
    //creates the pointers
    Node *first = nullptr;
    Node *second = nullptr;

    //create nodes using pointers
    first = new Node();
    second = new Node();

    //add names to nodes
    first->m_name = "Mike";
    second->m_name = "Ethan";

    //insert these pointers into a newly constructed linked list
    LinkedList MyList;
    MyList.InsertAtEnd(first);
    MyList.InsertAtEnd(second);
    MyList.Display();
    return 0;
}

您应该使用调试器逐步执行代码。在你的函数中

 void InsertAtEnd(Node *ptr) { //we must traverse to the end
        Node *temp = m_head;
        while (temp != nullptr) {
            temp = temp->m_next;
        }
        temp->m_next = ptr->m_next; // but temp is nullptr. BOOM
    }

你正在迭代直到 tempnullptr。但在那一点上,做 temp->m_next 是 UB。你需要在那之前停下来。另外,你应该 link 向上 ptr,而不是 ptr->m_next

 void InsertAtEnd(Node *ptr) { //we must traverse to the end
        Node *temp = m_head;
        while (temp->m_next != nullptr) { // look ahead
            temp = temp->m_next;
        }
        temp->m_next = ptr;  // just ptr
    }

当然,如果 linked 列表为空

,您还必须进行额外检查
 void InsertAtEnd(Node *ptr) { //we must traverse to the end
    if (m_head == nullptr)
         m_head = ptr;
    else {    
    Node *temp = m_head;
        while (temp != nullptr) {
            temp = temp->m_next;
        }
        temp->m_next = ptr->m_next;
    }
}

您似乎在 Display 函数中做了相反的事情。在那里你应该迭代直到 tempnullptr。否则你不会打印最后一个元素。

另外,请不要using namespace std;