algoritmauzmanı
TREN
3.2Doubly Linked List
Lesson 3.2.3

Inserting at the end

Inserting at the end puts a new at the back of the list. In a doubly linked list the new node is linked from both sides: the old last node points to it with its forward link, and it points back to the old last node. The idea is the same as inserting at the end of a singly linked list; there is just one more link.

What you will learn
  • How the list is walked to find the last node
  • How the two links of the new node are set, and why the empty list is handled separately
  • Why the operation is , and how it becomes when a pointer is kept
5 minTime O(n)Memory O(1)C · Java · Python

1Idea

If all we have is , the only way to reach the last node is to the list from the start. A called last starts at head and moves forward until it reaches the node whose next field is NULL. The node where it stops is the last node.

Then two links are set: the last node's field points to the new node, and the new node's field points to the last node. The new node's next field is NULL, because it is now the end of the list.

If the list is empty, there are no nodes to walk and the line last->next would read through NULL. In that case the new node becomes the only element: both of its links stay NULL and points to it.

2Step by step

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

NULLNULL12?0x1a407?0x1a903?0x1b209?0x2c10headnodelast
  1. Start. points to 12. The last node is 3 and its field is NULL.
  2. Memory is allocated for the new node, 9 is written into it and its field is set to NULL. The list is not empty, so the if block is skipped.
  3. The last starts at , that is, at 12.
  4. The field of 12 is not NULL, so last moves one step forward to 7.
  5. From 7 it moves on to 3. The field of 3 is NULL, so the loop ends. last now points to the last node.
  6. The last node's field is pointed at the new node. Going forward from 3 now reaches 9.
  7. The new node's field is linked to last, that is, to 3. Going back from 9 now reaches 3.
  8. Result: 12 ⇄ 7 ⇄ 3 ⇄ 9. The new node is linked into the list in both directions.

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

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

3Complexity

Time
O(n)

All n nodes are visited to find the last one. Setting the links takes constant time.

Memory
O(1)

No space is needed apart from the new node and a single last pointer.

If a pointer to the last node is kept, no walk is needed: tail->next = node; node->prev = tail; tail = node; makes it with three assignments. This is why doubly linked lists usually keep alongside .

4Common mistake

The most common mistake is forgetting to set the new node's field:

last->next = node;   // node->prev is never set

Walking forward then prints 12 7 3 9 and the list looks right. But in C malloc does not clear memory: the new node's field holds a random address. Code that walks back from the end follows that address and crashes or prints garbage. In Java and Python the field stays null; walking backward stops at 9 and never sees the rest of the list.

5Try it

If insertAtEnd is called on an empty list and the if block were missing, what would happen?

Show the answer

The answer is B. The line last = *head assigns NULL. The condition while (last->next != NULL) then tries to read a field of NULL; that is undefined behaviour and usually crashes the program. On an empty list the new node simply becomes .

If a tail pointer to the last node is kept, how many steps does inserting at the end take?

Show the answer

The answer is B. already points to the last node, so no walk is needed. Three assignments are made: the old last node's next field, the new node's prev field and tail itself. The time does not depend on the length of the list.

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