Computernerd
Computernerd

Reputation: 7766

Difference in adding of elements to linked list

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

Upvotes: 0

Views: 204

Answers (2)

Thomas Matthews
Thomas Matthews

Reputation: 57698

In your Addelement method, you need an else clause because if the list is empty (head == NULL), you only need to point the head to 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.

struct Node_Link
{
    Node_Link * next;
};

struct Node_Integer
: public Node_Link
{
    int data;
};

struct Node_Double
: public Node_Link
{
   double data;
};

struct Node_String
: public Node_Link
{
    std::string data;
};

Upvotes: 1

Bernhard Barker
Bernhard Barker

Reputation: 55609

At the end of addelementfromback, temp is a pointer to the last element in the list. If you were to say temp = element, this wouldn't change the list, since you're just giving a local pointer a new value.

temp->next, however, is the next variable stored inside the object temp points to (i.e. the last element in the list), you need to change this value to point to the new element.

For Addelement, temp is a pointer to the new element, you assign the pointer head to point to the same element, and change the next variable inside this pointed-to element to point to the original head.

Upvotes: 1

Related Questions