我不是编程新手,而是学习 C++。为此,我正在用 C++ 语言实现“标准”数据结构。我从链表开始。我了解它们是如何工作的以及所有这些。但是,当我尝试打印列表时,它并没有在应该停止的时候停止。我将最后一个指针设置为 nullptr 和所有这些,并在互联网上大量研究了这个问题,但我找不到我正在做的与其他人不同的事情。这是代码:
template<typename T>
void LinkedList<T>::print_list(){
list_node<T> *pos = this->start;
while(pos != nullptr){
cout << "PRInting" <<pos->data<<endl <<pos->next;
pos = pos->next;
}
}
这是完整的代码:
#ifndef LINKEDLIST_H_INCLUDED
#define LINKEDLIST_H_INCLUDED
#include <iostream>
using std::cout;
using std::endl;
template <class T>
struct list_node{
T data;
list_node<T> *next;
};
template <class T>
class LinkedList{
private:
list_node<T> *start;
public:
LinkedList();
LinkedList(T firstData);
~LinkedList();
void insert_item(T item);
void delete_item(T item);
list_node<T>* search_list();
void print_list();
};
//constructors and destructor
template <typename T>
LinkedList<T>::LinkedList(){
this->start = nullptr;
}
template <typename T>
LinkedList<T>::LinkedList(T firstData){
list_node<T> newNode = {
firstData,
nullptr
};
this->start = &newNode;
cout <<"Constructor" <<this->start->data<<endl;
}
template <typename T>
LinkedList<T>::~LinkedList(){
this->start = nullptr;
}
//Debugging print function
template<typename T>
void LinkedList<T>::print_list(){
list_node<T> *pos = this->start;
while(pos != nullptr){
cout << "PRInting" <<pos->data<<endl <<pos->next;
pos = pos->next;
}
//cout << pos->data;
}
//Operations on Linked Lists
template <typename T>
void LinkedList<T>::insert_item(T item){
list_node<T> *insertNode;
insertNode->data = item;
insertNode->next = this->start;
this->start = insertNode;
cout << "After insert " <<this->start->data << '\n' << this->start->next->data<<endl;
}
#endif // LINKEDLIST_H_INCLUDED
最佳答案
您的代码中存在关于节点插入的 2 个不同问题。
newNode
,并将其内存地址存储在 this->start
中。但是,newNode
对象将在离开构造函数的范围时被销毁,并且尝试取消引用它会导致 UB(未定义行为)。您应该动态分配节点,这样一旦离开范围就不会被销毁:LinkedList<T>::LinkedList(T firstData){
this->start = new list_node<T>;
this->start->data = firstData;
this->start->next = nullptr;
cout <<"Constructor" <<this->start->data<<endl;
}
insert_item
过程中:您正在取消引用本地指针 insertNode
,即使没有为其分配实际内存,并且取消引用它也会导致 UB。正确的版本看起来像:template <typename T>
void LinkedList<T>::insert_item(T item){
list_node<T> *insertNode = new list_node<T>;
insertNode->data = item;
insertNode->next = this->start;
this->start = insertNode;
cout << "After insert " <<this->start->data << '\n' << this->start->next->data<<endl;
}
start
分配给 nullptr
是不够的:template <typename T>
LinkedList<T>::~LinkedList(){
list_node<T> *pos = this->start;
while (pos != nullptr){
list_node<T>* nextPos = pos->next;
delete pos;
pos = nextPos;
}
}
关于C++ 链表打印崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41984302/