|
|
 
  |
Pictorially:
|
Code for inserting at tail of non-empty list
elem = new ListElem; // Make new object
elem->value = ...; // Fill elem with information
// Find the last element in the list
lastElem = head;
while (lastElem->next != NULL)
lastElem = lastElem->next;
// Link "elem" to lastElem:
lastElem->next = elem;
// Mark new elem as the last element:
elem->next = NULL;
|
Code for inserting at tail of non-empty list
elem = new ListElem;
elem->value = ...;
// Find the last element in the list
lastElem = head; // head == NULL
while (lastElem->next != NULL)
lastElem = lastElem->next;
lastElem->next = elem;
elem->next = NULL;
|
In the insertion at the TAIL of the list, there is only ONE exception case (empty list).
(Other type of inserts may have more exception cases...)
Complete algorithm to insert at tail of list
elem = new ListElem;
elem->value = ...;
if ( head == NULL ) // Detect and handle exception case....
{
head = elem;
elem->next = NULL;
}
else
{
// Find the last element in the list
lastElem = head;
while (lastElem->next != NULL)
lastElem = lastElem->next;
// Link "elem" to lastElem:
lastElem->next = elem;
// Mark new elem as the last element:
elem->next = NULL;
}
|