【发布时间】:2017-02-01 16:03:46
【问题描述】:
我不是编程新手,而是学习 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
【问题讨论】:
-
我将最后一个指针设置为 nullptr 从给出的示例中我们看不到这一点。请提供minimal reproducible example。
-
这个功能对我来说看起来不错。问题肯定出在其他地方。
-
如果您在崩溃前最后输出的行不是 0,那么您就没有空终止列表
-
其中一些 cout 语句仅用于我的调试目的。
标签: c++ data-structures linked-list