# Iterative Method to Insert at Tail of a Linked List

1. What do you want to achieve when you insert a new element at the tail of a linked list:

2. What do you need to do:

1. Find the last element in the list
• How can you tell which is the last element ???

2. Make the last element point to the new element (the new element will thus "follow" the old last element)

3. Set the "next" linkage variable in the new element to null to indicate the end of the list

 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; ```

3. Almost always, the insertion (and deletion) techniques to maintain linked lists would not work in special cases:

• The most common exceptional case is the empty list

4. EXCEPTION case for insert at tail:

• The above insert method does not work when the list is empty
• It's easy to see: if head == null --> lastElem == null --> lastElem.next does not exist

5. Handle EXCEPTION cases separately:

 Complete algorithm to insert at tail of list ``` elem = new ListElem(...); // Make new object elem.value = ...; // Fill elem with information if ( head == null ) { 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; } ```

6. A list class that manages insertion at tail

• Again, we should not let unindoctrinated users mess with the maintenance of the list.
• We deny them access to the list by making "head" private and provide them with service methods.

 A List class that maintains a list by inserting at tail... ``` public class List { private ListElem head; public List() { head = null; // empty list } // ************************************************* // insert(amount): make a listElem with value "v" // and insert listElem at tail... // ************************************************* public void insert(int v) { ListElem elem; elem = new ListElem(v); // Make ListElem object (elem.value = .... // optionally) if ( this.head == null ) { // Handle insert into empty list separately. head = elem; elem.next = null; } else { // Insert into non-empty list ListElem lastElem; // Find the last element in list lastElem = head; while (lastElem.next != null) lastElem = lastElem.next; last.next = elem; // Link new element to "last" elem elem.next = null; // Mark the end of the list } } } ```

7. DEMO programs