Adding to the end of a Doubly Linked Circular list

Should my if statement be

if (tail== NULL) or if(tail->next == tail) ?
It depends on what the rest of your code looks like.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void addtoTail(T element)
{
	Node<T>*temp, head; 
	temp->element= element;
	temp= new Node<T>*;
	if(tail->next == tail)
	{
		temp->next= temp; 
		temp->prev= temp; 
tail= temp;
               }
	else 
	{
		head= tail->next;
		tail->next= temp;
		temp->prev =tail;
		temp->next =head;
		tail= temp;
	} 
}


Can both statements work?
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.
Topic archived. No new replies allowed.