简体   繁体   English

如何将双向链接列表中的头部初始化为NULL?

[英]How do I initiliaze a head in a doubly-linked list to be NULL?

I have a homework to implement a doubly-linked list in C++ with two structs. 我有一个作业,用两个结构在C ++中实现一个双向链接列表。 One of them should hold the next and previous pointers , as well as the data. 其中一个应保存下一个和上一个指针以及数据。 The other struct should hold two pointers, one for the head and one for the tail 另一个结构应包含两个指针,一个指向头部,另一个指向尾部

Struct DlistElem{
    int data;
    DlistElem* next;
    DlistElem* prev;
  }

Struct Dlist{
 Dlist * head;
 Dlist * tail;
}

//some functions

the problem I'm having is I don't know how to initialize both the head and tail to be null in order to use them. 我遇到的问题是我不知道如何将头和尾都初始化为null才能使用它们。 Any help would be greatly appreciated! 任何帮助将不胜感激!

Initialize the pointers with NULL when you create a DlistElem and Dlist. 创建DlistElem和Dlist时,使用NULL初始化指针。

struct DlistElem{
    DlistElem* prev;
    DlistElem* next;
    int data;
    DlistElem() :
        prev(NULL),
        next(NULL),
        data()
    {}
}

struct Dlist{
    Dlist* head;
    Dlist* tail;
    Dlist() :
        head(NULL),
        tail(NULL)
    {}
}

I don't know how to initialize both the head and tail to be null in order to use them. 我不知道如何将头和尾都初始化为null才能使用它们。

struct DlistElem {
    int data;
    DlistElem* next;
    DlistElem* prev;

    DlistElem() : data{}, next{}, prev{}
    {}
};

or 要么

struct DlistElem {
    int data;
    DlistElem* next{};
    DlistElem* prev{};
};

Another way this can be done in c++11 is: 可以在c ++ 11中完成的另一种方法是:

struct DlistElem{
    int data;
    DlistElem* next = nullptr;
    DlistElem* prev = nullptr;
}

struct Dlist{
    Dlist * head = nullptr;
    Dlist * tail = nullptr;
}

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

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