简体   繁体   English

尝试以递归方式在 C++ 中打印链表

[英]Trying to print a linked list in c++ recursively

I've been trying to create an ordered double linked list and then print it out forwards and backwards using recursion.我一直在尝试创建一个有序的双链表,然后使用递归向前和向后打印出来。 I don't know if I'm adding nodes to the linked list incorrectly or if my problem is in my print functions.我不知道我是否错误地将节点添加到链表中,或者我的问题是否出在我的打印功能上。

Main主要的

int main() {
    ifstream addData;
    addData.open("proj1adds.data");
    LinkedList<int> List;
    Node<int> *head = NULL:
    int add;
    int i = 0;
    while (!addData.eof()){
        addData >> add;
        List.add(i, add);
        i++;
    }
}

this is my add function这是我的添加功能

template < typename T >
void LinkedList < T >::add(int index, T element)
{
  if (index == 0){
    addFirst(element);
  }
  else if (index >= size){
    addLast(element);
  }
  else
  {
    Node < T > * current = head;
    for (int i = 1; i < index; i++)
      current = current->next;
    Node < T > * temp = current->next;
    current->next = new Node < T > (element);
    (current->next)->prev = current;
    (current->next)->next = temp;
    size++;
  }
}    

And these are my print functions这些是我的打印功能

template<typename T>
void LinkedList<T>::printForward(Node<T> *head){
    if(head==NULL){
        return;
    }
    cout << head->element << endl;
    printForward(head->next);
}

template<typename T>
void LinkedList<T>::printBackward(Node<T> *head){
    if(head==NULL){
        return;
    }
    printBackward(head->next);
    cout << head->element << endl;
}

I think that I've loaded the data into the nodes, but I'm not sure if its ordered because I cant print it.我认为我已将数据加载到节点中,但我不确定它是否已订购,因为我无法打印它。

In a comment (but not in your question) you say that you're calling printFowards(head) and printBackwards(head) in main() .在评论中(但不是在您的问题中),您说您正在printFowards(head)调用printFowards(head)printBackwards(head) main() But in main() , the variable head is a local variable that is set to NULL .但是在main() ,变量head是一个设置为NULL的局部变量。 So the functions abort, and when you comment out the exit condition [ shudder ] you dereference a null pointer and get Undefined Behavior.所以函数中止,当你注释掉退出条件 [ shudder ] 时,你取消引用一个空指针并得到未定义的行为。

Maybe the list is being constructed correctly;也许列表正在构建正确; it doesn't matter because your calls to the printing functions have no connection to the list.没关系,因为您对打印功能的调用与列表没有联系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM