algoritmauzmanı
TREN
3.1Singly Linked List
Lesson 3.1.4

Inserting at the end

Inserting at the head does not depend on the length of the list. Inserting at the end is different: to find the end you first have to walk the whole list. This lesson shows how to link a new at the end of the list and why the empty list is handled separately.

What you will learn
  • How you walk to the last node and why the loop stops on the last node
  • Why changes when the list is empty and why that case is written separately
  • Why the operation is and how a pointer brings it down to
5 minTime O(n)Memory O(1)C · Java · Python

1Idea

To link a new node at the end, it is enough to write its address into the last node's field. The problem is that we do not know where the last node is. The list keeps only , so we start at the front and move until we find the node whose next field is .

This walk is like traversal with one difference: the loop runs on temp->next != NULL, not temp != NULL. That way temp stops on the last node before falling off to NULL, and the new node can be linked to it.

If the list is empty there is no last node and temp->next cannot be read. In that case the new node becomes both the first and the last node, so points to it. Because head changes, the C function takes struct Node**.

If you keep a pointer to the last node, there is no walk: you write tail->next = node; tail = node; and the operation is . In return you must keep tail up to date on every insertion and deletion.

2Step by step

The drawing adds 9 to the end of the list holding 12, 7 and 3. At each step the matching line of code lights up.

NULL12?0x1a407?0x1a903?0x1b209?0x2c10headnodetemp
  1. Start. points to the first node (12). The field of the last node, 3, is NULL.
  2. Memory is allocated for the new node () and 9 is written into it. It will go to the end, so its next field is .
  3. The list is not empty. temp takes the value of and starts walking from the first node.
  4. 12's next field is not NULL; temp moves one node and points to 7.
  5. temp moves to 3. 3's field is NULL, so the loop stops here: temp is on the last node.
  6. The new node's address is written into the last node's next field. 3 now points to 9.
  7. Result: 12 → 7 → 3 → 9 → NULL. did not change; only the last node's next field was updated.

struct Node {    int data;    struct Node* next;}; void insertAtEnd(struct Node** head, int value) {    struct Node* node = malloc(sizeof(struct Node));    node->data = value;    node->next = NULL;          // the new node will be last    if (*head == NULL) {        // empty list        *head = node;        return;    }    struct Node* temp = *head;    while (temp->next != NULL)        temp = temp->next;    temp->next = node;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} Node insertAtEnd(Node head, int value) {    Node node = new Node(value);    if (head == null) return node;  // empty list    Node temp = head;    while (temp.next != null)        temp = temp.next;    temp.next = node;    return head;}
class Node:    def __init__(self, data):        self.data = data        self.next = None def insert_at_end(head, value):    node = Node(value)    if head is None:  # empty list        return node    temp = head    while temp.next is not None:        temp = temp.next    temp.next = node    return head

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

Finding the last node means passing all n nodes. The linking itself takes constant time.

Memory
O(1)

Apart from the new node, only one helper pointer is used.

With a pointer the walk disappears and inserting at the end becomes . A queue built on a linked list keeps tail for exactly this reason.

4Common mistake

A common mistake is forgetting the empty list:

struct Node* temp = *head;while (temp->next != NULL)     // temp is NULL if the list is empty    temp = temp->next;temp->next = node;

When the list is empty, temp is and reading temp->next crashes the program. Check *head == NULL before the loop, and in that case point head at the new node.

5Try it

What happens if you change the loop condition to temp != NULL?

Show the answer

The answer is B. The temp != NULL condition walks past the last node too and moves temp to . The node we wanted to link to is lost. To stop on the last node you need temp->next != NULL.

On a list of 1000 nodes with no tail pointer, how many nodes are passed to insert at the end?

Show the answer

The answer is C. Finding the last node means passing every node from front to back. That is why the operation is . With a pointer there is no walk at all.

Lessons you mark show up in the curriculum. This is kept on this device only.