Should my if statement be
if (tail== NULL) or if(tail->next == tail) ?
It depends on what the rest of your code looks like.
The special cases are:
1. when the list is empty (head == nullptr)
2. when the list has one element
You can also help yourself by providing a constructor on Node, to keep your code simpler.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
template <typename T>
struct Node
{
T element;
Node *next, *prev;
Node(T e, Node *n = nullptr, Node *p = nullptr) :
element(e),
next(n),
prev(p)
{
}
};
|
It's tricky to explain without a diagram, but taking the normal case, when you have more than one element:
1 2 3 4 5
|
void addTail_notempty(T element)
{
Node* p = new Node(element, tail->next, tail);
tail = next->next = head->prev = p;
}
|
It seems that works if you have just 1 element too, so the only special case is when the list is empty:
1 2 3 4 5
|
void addTail_empty(T element)
{
Node *p = new Node(element);
head = tail = p->next = p->prev = p;
}
|
Do you understand why?
Last edited on
Some more hints:
You're accessing an uninitialzed pointer in line 4.
Do you really want to create a new Node pointer in line 5? Your compiler should have raised a warning on this line.
Line 14 shoildn't compile if next is a pointer.