You must first FIND the location of insertion before you can insert an element in a list. |
The last element of the list is identify by the value of the next field is NULL
ListElem *head; // Assume head is initialized.... ListElem *lastElem; // lastElem will point to the last element |
New links that you need to make:
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; |
|
Before insertion
head = NULL; |
After insertion
head = address of the new list element; |
|
(This is the case here with inserting at tail)
Fact: head = NULL; else points to a new List element |
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; } |
|
NOTE: we assume that the value in the list element has already been initialized (that is NOT part of the insert algorithm !)
|
|
ListElem * InsertAtTail(ListElem * head, ListElem * elem) { ListElem *lastElem; if ( head == NULL ) // Detect and handle exception case.... { elem->next = NULL; return(elem); // new head } 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; return(head); // new head } } |
int main(int argc, char *argv[]) { ListElem *head, *p; head = NULL; // Empty list p = new ListElem; p->value = 1500; head = InsertAtTail(head, p); // <--- record the new head in "head" } |
void InsertAtTail(ListElem * & head, ListElem * elem) { ListElem *lastElem; if ( head == NULL ) // Detect and handle exception case.... { elem->next = NULL; head = elem; // Return new head } else { // General case // 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; // Technically, we should return new head with the statement: // head = head; } } |
int main(int argc, char *argv[]) { ListElem *head, *p; head = NULL; // Empty list p = new ListElem; p->value = 1500; InsertAtTail(head, p); // <--- new head returned in "head" } |