试图在c++中递归地打印链表

Trying to print a linked list in c++ recursively

本文关键字:打印 链表 递归 c++      更新时间:2023-10-16

我一直在尝试创建一个有序的双链表,然后使用递归向前和向后打印出来。我不知道我是否错误地将节点添加到链表中,或者我的问题是在我的打印函数中。

主要

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++;
    }
}

这是我的add函数

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++;
  }
}    

这些是打印函数

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;
}

我认为我已经将数据加载到节点中,但我不确定它是否有序,因为我无法打印它。

在评论中(但不是在你的问题中),你说你在main()中调用printFowards(head)printBackwards(head)。但是在main()中,变量head是一个被设置为NULL的局部变量。所以函数中止,当你注释退出条件[shudder]时,你解引用一个空指针,得到未定义行为。

也许列表是正确构造的;这无关紧要,因为对打印函数的调用与列表没有连接。