所以,我创建了一个新的链表,我无法在链接列表的末尾插入一个新的节点。我试图通过列表遍历的不同迭代,但我认为问题出在哪里,我试图插入节点结束。
#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
}
你迭代,直到temp
为nullptr
。但在这一点上,做的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
IS nullptr
。否则,你将无法打印的最后一个元素。
另外,请不要做 using namespace std;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句