Estou recebendo uma falha de segmentação (núcleo) de erro ao tentar adicionar um nó para o final de uma lista ligada em c ++

AG8:

Então, eu criei uma nova lista ligado e eu estou tendo problemas para inserir um novo nó no final da lista encadeada. Eu tentei diferentes iterações de percorrer através da lista, mas eu acho que o problema é no final, onde eu estou tentando inserir o nó.

#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;
}
cigien:

Você deve usar um depurador para percorrer seu código. Em sua função

 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
    }

você está repetindo até que tempé nullptr. Mas nesse ponto, fazendo temp->m_nexté UB. Você precisa parar um pouco antes disso. Além disso, você deve ligar-se ptr, nãoptr->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
    }

Claro, você também tem que fazer uma verificação adicional no caso da lista ligada está vazia

 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;
    }
}

Você parece estar fazendo a coisa oposta na sua função Display. Lá você deve iterar até que tempseja nullptr. Caso contrário, você não vai imprimir o último elemento.

Além disso, por favor não faça using namespace std;

Acho que você gosta

Origin http://10.200.1.11:23101/article/api/json?id=377188&siteId=1
Recomendado
Clasificación