c++ - 使用函数在 LinkedList 中获取输入,但在打印时给出分段错误错误
问题描述
这是一个循环双向链表,但它在运行程序时给出了Segmentation Fault的运行时错误。函数的使用是接受输入直到用户给出 -1 和打印函数打印直到 cur->next == head。请告诉我我做错了什么,这样我以后就不会这样做了。谢谢你!
#include<iostream>
using namespace std;
template<class T>
class CDNode{
public:
T data;
CDNode* next;
CDNode* prev;
CDNode(T x){
data = x;
next = nullptr;
prev = nullptr;
}
};
template<typename T>
CDNode<T>* takeInput(){
cout<<"Enter the elements of the list"<<endl;
T data;
cin>>data;
CDNode<T> *head = nullptr;
CDNode<T> *tail = nullptr;
while(data != -1){
CDNode<T> *newNode = new CDNode<T>(data);
if(head == nullptr){
head = newNode;
tail = newNode;
}else{
tail->next = newNode;
newNode->prev = tail;
tail = tail->next;
}
cin>>data;
}
return head;
}
template<typename T>
void print(CDNode<T> *head,CDNode<T> *cur){
if(cur->next == head){
cout<<cur->data<<endl;
return;
}
cout<<cur->data<<" <- ";
return print(head,cur->next);
}
int main(){
CDNode<int> *head = takeInput<int>();
print(head,head);
}
解决方案
在循环列表中 tail->next 应该指向头节点,使其循环。您的代码只是一个双列表。
推荐阅读
- python - Keras:了解嵌入层在条件 GAN 中的作用
- odbc - 如何为 AccredoSuturn 创建 ODBC DSN 或 Accredo 的 ODBC 连接字符串是什么?
- html - 有没有办法将 html 类名指定为偶数(不奇数)以获得偶数 css 属性?
- javascript - 底部选项卡导航器背景图像
- java - 在 android 导航中禁用或隐藏主页和最近按钮
- python - 检查熊猫中的时间戳
- angular - Ionic 3 从选定日期设置日期并在日期中设置间隔
- python - 使用python将逗号分隔值转换为逗号分隔值
- django - 无法访问我通过 ssh 连接到的服务器上的开发服务器
- spring-boot - 检索作为卷挂载的 Kubernetes Secret