Solving the Circular Linked List Confusion (Insertion) ★
If you’re inserting nodes into a linked list, it’s quite simple if you’re doing it in a linear linked list(single or double ended). But when we talk about circular linked lists, it’s complexity increases slightly just because you’re now supposed to perform all operations using just one static pointer(the first or the last node of the linked list).
Linear linked lists have both the First(or Head) and Last(or Tail) pointers while circular linked lists have only either one of them, not both. First and Last are used, as the names suggest, as pointers to the first and last nodes of a linked list. In circular linked lists, even though we can use both pointers, doing so only destroys our purpose of making the linked list circular. The reason it is circular is because we can use just one static pointer to traverse the whole list.
Simple Insertion:
1. Insertion at Head using Head pointer
void LinkedList::AddToHead(int el)
{
if (head==0)
{
head=new IntNode(el);
head->next=head;
head->previous=head;
}
else
{
head->previous=new IntNode(el, head, head->previous)
head=head->previous;
head->previous->next=head;
}
}
2. Insertion at Tail using Tail pointer
void LinkedList::AddToTail(int el)
{
if (tail==0)
{
tail=new IntNode(el);
tail->next=head;
tail->previous=head;
}
else
{
tail->next=new IntNode(el, tail->next, tail)
tail=tail->next;
tail->next->previous=tail;
}
}
What’s getting people confused:
1. Insertion at Head using Tail pointer.
void LinkedList::AddToHead(int el)
{
if (tail==0)
{
tail=new IntNode(el);
tail->next=tail;
tail->previous=tail;
}
else
{
tail->next=new IntNode(el, tail->next, tail)
tail->next->next->previous=tail->next;
}
}
2. Insertion at Tail using Head pointer.
void LinkedList::AddToTail(int el)
{
if (head==0)
{
head=new IntNode(el);
head->next=head;
head->previous=head;
}
else
{
head->previous=new IntNode(el, head, head->previous)
head->previous->previous->next=head->previous;
}
}
Whether we insert at head or tail, it is important to note that in the correct implementation of the circular linked list the functions we use must use only either head or the tail pointers depending on the programmer’s choice. I’ve used a double ended linked list for this post, as anything simpler can be derived from it.
I’ve noticed that most people use both the head and tail pointers. I cannot verify the correctness of such programming but I don’t really see any point of using a circular list with both these pointers.
Other Links:
http://www.brpreiss.com/books/opus5/html/page165.html