尝试在 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;
}
}

您在显示功能中似乎在做相反的事情。在那里,您应该进行迭代,直到temp变成nullptr。否则将不会打印最后一个元素。

另外,请不要进行using namespace std;

相关内容

  • 没有找到相关文章

最新更新