0

I have a homework to implement a doubly-linked list in C++ with two structs. 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. Any help would be greatly appreciated!

3 Answers3

0

Initialize the pointers with NULL when you create a DlistElem and Dlist.

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)
    {}
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
0

I don't know how to initialize both the head and tail to be null in order to use them.

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

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

or

struct DlistElem {
    int data;
    DlistElem* next{};
    DlistElem* prev{};
};
Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • One thing I forgot to mention is, how do I later on access it some methods ? – Tonislav Tachev Nov 10 '18 at 23:30
  • @TonislavTachev What is "on access it some methods ?" ? – Swordfish Nov 11 '18 at 05:23
  • @TonislavTachev The same way you access all other struct members? Not sure what your problem is. – eesiraed Nov 11 '18 at 05:26
  • Since I want to use the head in let's say an InsertAtFirst() method, where I first check if the head is null, afterwards if it is I'll proceed to add a new node. But I'm getting an error message, saying that head wasn't defined in this scope – Tonislav Tachev Nov 11 '18 at 11:07
  • @TonislavTachev comments are not for questions. if you have another question, go and ask another question. – Swordfish Nov 11 '18 at 11:23
0

Another way this can be done in c++11 is:

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

struct Dlist{
    Dlist * head = nullptr;
    Dlist * tail = nullptr;
}
Patrick
  • 375
  • 3
  • 12