Appending nodes to the tail
What you'll learn: How to add a new piece of data to the very end of your linked list by traversing from the start.
The "Passing the Baton" Analogy
Imagine a line of people holding hands. Each person knows only the person directly in front of them. If you want to add a new person to the very end of the line, you can't just jump there—you don't know where the end is yet!
You must start at the very first person (the Head) and ask, "Are you the last person?" If they are holding someone else's hand, the answer is "No." You then move to the person they are holding. You repeat this until you find someone whose hand is empty (NULL). That is the tail, and that is where the new person joins.
How it works in C
To append a node, we follow three steps:
- Create the new node: Allocate memory and set its
nextpointer toNULL(since it will be the new end). - Handle the empty list: If the list is empty, the new node simply becomes the
head. - Traverse to the end: If the list isn't empty, create a temporary "current" pointer to walk through the list until
current->nextisNULL.
Code Example
Here is how you implement the append logic:
struct Node {
int data;
struct Node* next;
};
void append(struct Node** head_ref, int new_data) {
// 1. Prepare the new node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
// 2. If the list is empty, make this the head
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
// 3. Otherwise, traverse to the last node
struct Node* last = *head_ref;
while (last->next != NULL) {
last = last->next;
}
// 4. Change the next of the last node
last->next = new_node;
}
Why the while loop matters
Unlike an array where you can jump to array[last_index], a linked list requires a "walk." The while (last->next != NULL) loop is the heartbeat of this process. It stops exactly at the last node, ensuring you don't fall off the end of the list into NULL space, but rather stay on the last valid node so you can update its next pointer to include your new arrival.
Key takeaway
To append to a list, you must start at the head and follow the "next" links until you find the node that points to NULL.