This is how i add elements to the head of a linked list
//typedef void* VoidPtr
//typedef node* NodePtr
struct Node
{
NodePtr next
VoidPtr data
};
void LinkedList::Addelement(VoidPtr horoscope)
{
if(head == NULL)
{
head = new Node;
head->data = horoscope;
head->next = NULL;
}
NodePtr temp = new Node;
temp -> data = horoscope;
temp -> next = head;
head = temp;
}
This is how i add elements to the tail of a linked list
void LinkedList::addelementfromback(VoidPtr horoscope)
{
NodePtr temp=head;
if(head == NULL)
{
head = new Node;
head->data = horoscope;
head->next = NULL;
}
while( temp->next != NULL)
{
temp=temp->next
}
NodePtr element=New Node;
element->data=horoscope;
element->next=NULL;
temp->next=element;
}
i dont understand why we use temp=element for adding to the head of a linked list
but for adding to the tail of a linked list we use temp->next=element. I dont understand why we cant use while temp=next for adding element to tail of linked list
In your
Addelementmethod, you need anelseclause because if the list is empty (head == NULL), you only need to point theheadto the new node. Nothing else, there are no other nodes in the list.Also, rather than using a void pointer, consider using templates. Templates are great for data structures and algorithms where the data type changes, not the structure or algorithm, such as stacks and linked lists.
I suggest you consider separating the node pointers from the data item as two separate structures. This will help you use common code between single linked lists and doubly linked lists. Also a great help when you don’t want to use templates.