algoritmauzmanı
TREN
3.3Circular Linked List
Lesson 3.3.2

Inserting a node

Inserting at the head of a singly linked list took two assignments. In a the last node points to the first, so every node added at the front changes the last node's link too. In this lesson you will see inserting at the head and at the end together; they differ by a single line.

What you will learn
  • Why the last node's next field has to be updated when inserting at the head
  • That inserting at the end differs from inserting at the head only in leaving head where it is
  • How the first node goes into an empty list, and why the operation is O(n)
7 minTime O(n)Memory O(1)C · Java · Python

1Idea

In a circular list the field of the last node points to . When a new node comes in at the front, the first node changes, so the last node's link must be moved to the new node as well. We have no to the last node; we find it by starting at head and moving on until we reach the node whose next is head.

Once the last node is found, inserting at the head takes three assignments: the new node points to the old first node, the last node points to the new node, and head moves to the new node.

Inserting at the end makes the same two links but leaves head alone. In a ring, "the end" is the spot just before head; once the new node sits between the last node and head, it is the new end of the list:

node->next = *head;   // the new node points back to the startlast->next = node;    // the old last node points to the new node// head does not change: 12 7 3 5

If the list is empty, both functions do the same thing: the new node's next points to itself and head becomes the new node. That is a one-node ring.

2Step by step

The drawing adds 5 to the front of a circular list holding 12, 7 and 3. The link from the last node back to the first curves under the row. At each step the matching line of code lights up.

5?12?7?3?headnodelast
  1. Start. points to 12. The field of the last node, 3, goes back to 12; there is no NULL in the list.
  2. Memory is allocated for the new node () and 5 is written into it. The list is not empty, so the if block is skipped. The new node is not part of the ring yet.
  3. To find the last node, the last pointer starts at head.
  4. The next field of 12 is not head, so last moves on to 7.
  5. The next field of 7 is not head either, so last moves to 3. The next field of 3 is head; the loop stops. The last node has been found.
  6. head is written into the new node's next field. 5 now points to 12.
  7. The last node's next field is moved to the new node. The link coming back from 3 now goes to 5 instead of 12; the ring has taken in the new node.
  8. head moves to the new node. Result: 5 → 12 → 7 → 3, and 3 points back to 5. When inserting at the end, this last step is skipped.

struct Node {    int data;    struct Node* next;}; void insertAtHead(struct Node** head, int value) {    struct Node* node = malloc(sizeof(struct Node));    node->data = value;    if (*head == NULL) {          // empty list        node->next = node;        // a single node points to itself        *head = node;        return;    }    struct Node* last = *head;    while (last->next != *head)   // find the last node        last = last->next;    node->next = *head;    last->next = node;    *head = node;} void insertAtEnd(struct Node** head, int value) {    struct Node* node = malloc(sizeof(struct Node));    node->data = value;    if (*head == NULL) {        node->next = node;        *head = node;        return;    }    struct Node* last = *head;    while (last->next != *head)        last = last->next;    node->next = *head;    last->next = node;            // head stays where it is}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} Node insertAtHead(Node head, int value) {    Node node = new Node(value);    if (head == null) {           // empty list        node.next = node;         // a single node points to itself        return node;    }    Node last = head;    while (last.next != head)     // find the last node        last = last.next;    node.next = head;    last.next = node;    return node;                  // the new head} Node insertAtEnd(Node head, int value) {    Node node = new Node(value);    if (head == null) {        node.next = node;        return node;    }    Node last = head;    while (last.next != head)        last = last.next;    node.next = head;    last.next = node;    return head;                  // head does not change}
class Node:    def __init__(self, data):        self.data = data        self.next = None def insert_at_head(head, value):    node = Node(value)    if head is None:              # empty list        node.next = node          # a single node points to itself        return node    last = head    while last.next is not head:  # find the last node        last = last.next    node.next = head    last.next = node    return node  # the new head def insert_at_end(head, value):    node = Node(value)    if head is None:        node.next = node        return node    last = head    while last.next is not head:        last = last.next    node.next = head    last.next = node    return head  # head does not change

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

3Complexity

Time
O(n)

Finding the last node visits every node in the list once. Making the links takes constant time.

Memory
O(1)

Space is allocated only for the new node and a few pointers.

Compare: inserting at the head of a singly linked list is . If a circular list keeps a pointer to its last node (), both insertions become O(1) as well; that variant is mentioned in What is a circular linked list?.

4Common mistake

The most common mistake is writing the head insertion as in a singly linked list and forgetting the last node:

node->next = *head;*head = node;   // last->next still points to the old head

The last node keeps pointing to 12 and 5 is left outside the ring. A that starts at head goes 5, 12, 7, 3, 12, 7, 3... and never comes back to head, so a loop that stops on returning to head never ends.

5Try it

What should the next field of the first node added to an empty list point to?

Show the answer

The answer is B. A single node is both the first and the last, and the last node points to the first. So its field points to itself. If it is left as NULL, the list is not circular and a traversal that stops on returning to head breaks.

What is the difference between the code for inserting at the head and at the end?

Show the answer

The answer is B. In both operations the new node goes between the last node and . If head moves to it, it becomes the head; if head stays, it becomes the last node.

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