Lesson 5 of 14

Push Back

Inserting at the Back

Appending to the end of a list requires traversing to the last node — O(n).

Walk until you find the node whose next is NULL, then attach the new node:

struct Node *push_back(struct Node *head, int val) {
    struct Node *n = new_node(val);
    if (head == NULL) return n;
    struct Node *cur = head;
    while (cur->next != NULL)
        cur = cur->next;
    cur->next = n;
    return head;
}
Before: [1] -> [2] -> NULL
After:  [1] -> [2] -> [3] -> NULL   (push_back(head, 3))

Empty List Edge Case

If head is NULL, the new node IS the list — return it directly.

Head Doesn't Change

Unlike push_front, appending doesn't change the head. We still return head so callers can use the same pattern (head = push_back(head, val)).

Your Task

Implement struct Node *push_back(struct Node *head, int val) that appends a node to the end and returns the head.

TCC compiler loading...
Loading...
Click "Run" to execute your code.