双向链表初始化

doubly linked lists initiallisation

你好所以我对链表和数据结构通常是新手所以我想创建两个函数一个初始化双向链表另一个打印它但是当我编译它时它不打印任何东西我在哪里完全错过了(我听说我应该使用调试器,但我不明白如何在 Dev c++ 上使用它 IDE)

  #include <iostream>
#include <stdlib.h>
using namespace std;
struct Node
{   int data;
    Node *next;
    Node *previous;
};
Node *head,*end;


Node* insertion()
{   
    Node *first_node =new Node;
    if (head==NULL || first_node==NULL)
        exit(EXIT_FAILURE);
        
    first_node->data=10;
    first_node->previous=NULL;
    first_node->next=NULL;
    head=first_node;
    end=first_node;
    return head;
}
void affiche()
{
    Node *current;
    current=head;
    if(head==NULL)
     exit(EXIT_FAILURE);
    while(current->next!=NULL)
    {
        cout<<current->data <<" ";
        current=current->next;
    }
}
int main()
{

    Node *MyList=insertion();
    affiche();
    return 0;
}

改变一下

while(current->next!=NULL)

while(current!=NULL)

您的版本过早停止打印列表。

(但是请学习如何使用调试器,使用调试器你会很快发现这个错误)。

编辑

你还需要删除这个

if (head==NULL || first_node==NULL)
    exit(EXIT_FAILURE);

head==NULL 最初为真,而 first_node==NULL 永远不会为真。 (new 从不 returns NULL)。由于 head==NULL 最初为真,因此您的程序总是会在该点退出。

编辑(2)

并删除这个

if(head==NULL)
   exit(EXIT_FAILURE);

为什么你认为打印一个空列表是一个错误,意味着你必须退出程序?打印一个空列表是完全可以的。