Skip to content
Laviyx Learn

Try

DS Lab · Experiment 3

Circular linked list operations

CLinked listsJNTUH R22 · CS306PC

Aim

To write a menu-driven C program that uses functions to create a circular singly linked list, insert a node at the beginning, at the end or at a given position, delete a node by position or by value, and traverse the list.

Algorithm

  1. Define a node with data and next. Keep a pointer last to the last node. In a circular list last->next is the first node, so one pointer gives both ends. An empty list has last = NULL.
  2. Create: read n values and insert each one at the end.
  3. Insert at beginning: if the list is empty, the new node points to itself and becomes last. Otherwise set new->next = last->next and last->next = new.
  4. Insert at end: link the new node after last in the same way, then make the new node last.
  5. Insert at position p: walk from the first node to node p − 1 and link the new node after it.
  6. Delete: start a pointer prev at last and move it until prev->next is the node to delete. Set prev->next to the node after it. If the deleted node was last, make prev the new last; if it was the only node, the list becomes empty. Free the node.
  7. Traverse: start at last->next and print nodes with a do-while loop until we come back to the first node.
  8. Repeat the menu until Exit, then free every node.

Program

C
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

struct node *create_node(int value) {
    struct node *newnode = malloc(sizeof(struct node));
    if (newnode == NULL) {
        printf("Memory not available\n");
        exit(1);
    }
    newnode->data = value;
    newnode->next = NULL;
    return newnode;
}

int count_nodes(struct node *last) {
    if (last == NULL) {
        return 0;
    }
    int count = 0;
    struct node *temp = last->next;
    do {
        count++;
        temp = temp->next;
    } while (temp != last->next);
    return count;
}

void display(struct node *last) {
    if (last == NULL) {
        printf("List is empty\n");
        return;
    }
    struct node *first = last->next;
    struct node *temp = first;
    printf("List: ");
    do {
        printf("%d -> ", temp->data);
        temp = temp->next;
    } while (temp != first);
    printf("(back to %d)\n", first->data);
}

/* Each function returns the new value of last */
struct node *insert_begin(struct node *last, int value) {
    struct node *newnode = create_node(value);
    if (last == NULL) {
        newnode->next = newnode;        /* single node points to itself */
        return newnode;
    }
    newnode->next = last->next;
    last->next = newnode;
    return last;
}

struct node *insert_end(struct node *last, int value) {
    struct node *newnode = create_node(value);
    if (last == NULL) {
        newnode->next = newnode;
        return newnode;
    }
    newnode->next = last->next;
    last->next = newnode;
    return newnode;                     /* new node is the new last */
}

struct node *insert_at(struct node *last, int value, int pos) {
    int count = count_nodes(last);
    if (pos < 1 || pos > count + 1) {
        printf("Invalid position\n");
        return last;
    }
    if (pos == 1) {
        return insert_begin(last, value);
    }
    if (pos == count + 1) {
        return insert_end(last, value);
    }
    struct node *temp = last->next;     /* first node */
    for (int i = 1; i < pos - 1; i++) {
        temp = temp->next;
    }
    struct node *newnode = create_node(value);
    newnode->next = temp->next;
    temp->next = newnode;
    return last;
}

/* Remove the node after prev and free it */
struct node *remove_after(struct node *last, struct node *prev) {
    struct node *del = prev->next;
    printf("Deleted %d\n", del->data);
    if (del == prev) {                  /* it was the only node */
        free(del);
        return NULL;
    }
    prev->next = del->next;
    if (del == last) {
        last = prev;
    }
    free(del);
    return last;
}

struct node *delete_at(struct node *last, int pos) {
    if (pos < 1 || pos > count_nodes(last)) {
        printf("Invalid position\n");
        return last;
    }
    struct node *prev = last;           /* the node before position 1 is last */
    for (int i = 1; i < pos; i++) {
        prev = prev->next;
    }
    return remove_after(last, prev);
}

struct node *delete_value(struct node *last, int value) {
    struct node *prev = last;
    do {
        if (prev->next->data == value) {
            return remove_after(last, prev);
        }
        prev = prev->next;
    } while (prev != last);
    printf("%d not found in the list\n", value);
    return last;
}

void free_list(struct node *last) {
    if (last == NULL) {
        return;
    }
    struct node *temp = last->next;
    last->next = NULL;                  /* break the circle first */
    while (temp != NULL) {
        struct node *next = temp->next;
        free(temp);
        temp = next;
    }
}

int read_int(const char *prompt, int *x) {
    printf("%s", prompt);
    return scanf("%d", x) == 1;
}

struct node *create_list(struct node *last) {
    int n, value;
    free_list(last);                    /* start a fresh list */
    last = NULL;
    if (!read_int("Enter number of nodes: ", &n) || n < 1) {
        printf("Invalid number of nodes\n");
        return NULL;
    }
    printf("Enter %d values: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &value) != 1) {
            printf("Invalid input\n");
            break;
        }
        last = insert_end(last, value);
    }
    return last;
}

int main(void) {
    struct node *last = NULL;
    int choice, value, pos;

    printf("CIRCULAR LINKED LIST\n");
    printf("1. Create list\n2. Insert at beginning\n3. Insert at end\n");
    printf("4. Insert at position\n5. Delete at position\n6. Delete by value\n");
    printf("7. Display\n8. Exit\n");

    do {
        if (!read_int("\nEnter your choice: ", &choice)) {
            printf("Invalid input\n");
            break;
        }
        switch (choice) {
        case 1:
            last = create_list(last);
            display(last);
            break;
        case 2:
            if (read_int("Enter value: ", &value)) {
                last = insert_begin(last, value);
                display(last);
            }
            break;
        case 3:
            if (read_int("Enter value: ", &value)) {
                last = insert_end(last, value);
                display(last);
            }
            break;
        case 4:
            if (read_int("Enter value: ", &value) && read_int("Enter position: ", &pos)) {
                last = insert_at(last, value, pos);
                display(last);
            }
            break;
        case 5:
            if (last == NULL) {
                printf("List is empty, nothing to delete\n");
            } else if (read_int("Enter position: ", &pos)) {
                last = delete_at(last, pos);
                display(last);
            }
            break;
        case 6:
            if (last == NULL) {
                printf("List is empty, nothing to delete\n");
            } else if (read_int("Enter value to delete: ", &value)) {
                last = delete_value(last, value);
                display(last);
            }
            break;
        case 7:
            display(last);
            printf("Number of nodes: %d\n", count_nodes(last));
            break;
        case 8:
            break;
        default:
            printf("Invalid choice\n");
        }
    } while (choice != 8);

    free_list(last);
    printf("All nodes freed. Exiting.\n");
    return 0;
}

Output

Output
CIRCULAR LINKED LIST
1. Create list
2. Insert at beginning
3. Insert at end
4. Insert at position
5. Delete at position
6. Delete by value
7. Display
8. Exit

Enter your choice: 5
List is empty, nothing to delete

Enter your choice: 1
Enter number of nodes: 3
Enter 3 values: 10 20 30
List: 10 -> 20 -> 30 -> (back to 10)

Enter your choice: 2
Enter value: 5
List: 5 -> 10 -> 20 -> 30 -> (back to 5)

Enter your choice: 3
Enter value: 40
List: 5 -> 10 -> 20 -> 30 -> 40 -> (back to 5)

Enter your choice: 4
Enter value: 25
Enter position: 4
List: 5 -> 10 -> 20 -> 25 -> 30 -> 40 -> (back to 5)

Enter your choice: 5
Enter position: 5
Deleted 30
List: 5 -> 10 -> 20 -> 25 -> 40 -> (back to 5)

Enter your choice: 6
Enter value to delete: 5
Deleted 5
List: 10 -> 20 -> 25 -> 40 -> (back to 10)

Enter your choice: 5
Enter position: 4
Deleted 40
List: 10 -> 20 -> 25 -> (back to 10)

Enter your choice: 6
Enter value to delete: 99
99 not found in the list
List: 10 -> 20 -> 25 -> (back to 10)

Enter your choice: 7
List: 10 -> 20 -> 25 -> (back to 10)
Number of nodes: 3

Enter your choice: 8
All nodes freed. Exiting.

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

The program keeps a pointer to the last node instead of the first. Since last->next is the first node, inserting at either end takes O(1) time without walking the list.

A circular list has no NULL at the end, so every loop must stop when it comes back to its starting node. That is why display, count_nodes and delete_value use do-while loops. Before freeing, free_list breaks the circle by setting last->next = NULL, so the freeing loop has an end.

Common mistakes

  • Using while (temp != NULL) to traverse. In a circular list temp never becomes NULL, so the loop runs forever. Stop when you are back at the first node.

  • Using a while loop that checks temp != first before printing. It stops at once because temp starts at first, so nothing is printed. Use a do-while loop.

  • Forgetting to update last when the last node is deleted, so last points to freed memory.

  • Forgetting that a single node must point to itself (newnode->next = newnode).

Viva questions

Try to answer each one aloud before you open it.

  • What is a circular linked list?

    It is a linked list in which the last node's next pointer points back to the first node instead of NULL, so the nodes form a circle.

  • Why do we keep a pointer to the last node rather than the first?

    From last we reach the first node in one step as last->next. So we can insert at the beginning and at the end in O(1) time with a single pointer.

  • How do you know you have visited every node in a circular list?

    Remember the starting node and stop when the traversal comes back to it.

  • Where are circular linked lists used?

    In round-robin CPU scheduling, where each process gets a turn and then the first comes again, in multiplayer turn order, and in circular buffers.

  • How do you check whether a list is empty in this program?

    The list is empty when last is NULL. A list with one node has last->next == last.

Learn the concepts

All Data Structures Lab experiments →