簡體   English   中英

嘗試將節點添加到 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。 你需要在那之前停下來。 此外,您應該鏈接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
    }

當然,如果鏈表為空,你還必須做額外的檢查

 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM