首页 > 解决方案 > 使用函数在 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);
    }

标签: c++functionlinked-listruntime-error

解决方案


在循环列表中 tail->next 应该指向头节点,使其循环。您的代码只是一个双列表。


推荐阅读