The Wayback Machine - https://web.archive.org/web/20240828110620/https://www.geeksforgeeks.org/circular-singly-linked-list-insertion/
Open In App

Insertion in Circular Singly Linked List

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn how to insert a node to a circular linked list. In a circular linked list, the last node connects back to the first node, creating a loop.

There are four main ways to add items:

  • Insertion in an empty list
  • Insertion at the beginning of the list
  • Insertion at the end of the list
  • Insertion at specific position in the list

Now, let’s look at the methods and steps for these four insertion operations.

Advantage of using a tail pointer instead of head pointer

For the insertion of a node at the beginning, we need to traverse the whole list. Also, for insertion at the end, the whole list has to be traversed. If instead of the start pointer, we take a pointer to the last node, then in both cases there won’t be any need to traverse the whole list. So insertion at the beginning or at the end takes constant time, irrespective of the length of the list.

Insertion in the circular linked list:

Insertion is a fundamental operation in linked lists that involves adding a new node to the list. The only extra step is connecting the last node to the first one. In the circular linked list mentioned below, we can insert nodes in four ways:

1. Insertion in an empty List in the circular linked list

To insert a node in empty circular linked list, creates a new node with the given data, sets its next pointer to point to itself, and updates the last pointer to reference this new node.

Insertion-in-an-empty-list-in-circular-linked-list

Insertion in an empty List

Step-by-step approach:

  • Check if last is not nullptr. If true, return last (the list is not empty).
  • Otherwise, Create a new node with the provided data.
    • Set the new node’s next pointer to point to itself (circular link).
    • Update last to point to the new node and return it.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

struct Node{
    int data;
    Node *next;
    Node(int value){
        data = value;
        next = nullptr;
    }
};

// Function to insert a node into an empty circular singly linked list
Node *insertInEmptyList(Node *last, int data){
    if (last != nullptr) return last;
    
    // Create a new node
    Node *newNode = new Node(data);
  
    // Point newNode to itself
    newNode->next = newNode;
  
    // Update last to point to the new node
    last = newNode;
    return last;
}

void printList(Node* last){
    if(last == NULL) return;
  
    // Start from the head node
    Node* head = last->next;
    while (true) {
        cout << head->data << " ";
        head = head->next;
        if (head == last->next) break;
    }
    cout << endl;
}

int main(){
    Node *last = nullptr;

    // Insert a node into the empty list
    last = insertInEmptyList(last, 1);

    // Print the list
    cout << "List after insertion: ";
    printList(last);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Define the Node structure
struct Node {
    int data;
    struct Node* next;
};

struct Node* createNode(int value);

// Function to insert a node into an empty
// circular singly linked list
struct Node* insertInEmptyList(struct Node* last, int data) {
    if (last != NULL) return last;

    // Create a new node
    struct Node* newNode = createNode(data);

    // Update last to point to the new node
    last = newNode;
    return last;
}

void printList(struct Node* last) {
    if (last == NULL) return;

    // Start from the head node
    struct Node* head = last->next;
    while (1) {
        printf("%d ", head->data);
        head = head->next;
        if (head == last->next) break;
    }
    printf("\n");
}

struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->next = newNode;
    return newNode;
}

int main() {
    struct Node* last = NULL;

    // Insert a node into the empty list
    last = insertInEmptyList(last, 1);

    // Print the list
    printf("List after insertion: ");
    printList(last);

    return 0;
}
Java
class Node {
    int data;
    Node next;

    Node(int value) {
        data = value;
        next = null;
    }
}

public class Main {
    // Function to insert a node into an empty
    // circular singly linked list
    static Node insertInEmptyList(Node last, int data) {
        if (last != null) return last;

        // Create a new node
        Node newNode = new Node(data);

        // Point newNode to itself
        newNode.next = newNode;

        // Update last to point to the new node
        last = newNode;
        return last;
    }

    // Function to print the list
    static void printList(Node last) {
        if (last == null) return;

        // Start from the head node
        Node head = last.next;
        while (true) {
            System.out.print(head.data + " ");
            head = head.next;
            if (head == last.next) break;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Node last = null;

        // Insert a node into the empty list
        last = insertInEmptyList(last, 1);

        // Print the list
        System.out.print("List after insertion: ");
        printList(last);
    }
}
Python
class Node:
    def __init__(self, value):
        self.data = value
        self.next = self  # Point to itself

def insertInEmptyList(last, data):
    if last is not None:
        return last
    
    # Create a new node
    new_node = Node(data)
    
    # Update last to point to the new node
    last = new_node
    return last

def printList(last):
    if last is None:
        return
    
    # Start from the head node
    head = last.next
    while True:
        print(head.data, end=" ")
        head = head.next
        if head == last.next:
            break
    print()

if __name__ == "__main__":
    last = None

    # Insert a node into the empty list
    last = insertInEmptyList(last, 1)

    # Print the list
    print("List after insertion: ", end="")
    printList(last)
JavaScript
class Node {
    constructor(value)
    {
        this.data = value;
        this.next = null;
    }
}

function insertInEmptyList(last, data)
{
    if (last !== null)
        return last;

    // Create a new node
    let newNode = new Node(data);

    // Point newNode to itself
    newNode.next = newNode;

    // Update last to point to the new node
    last = newNode;
    return last;
}

function printList(last)
{
    if (last === null)
        return;

    // Start from the head node
    let head = last.next;
    while (true) {
        console.log(head.data);
        head = head.next;
        if (head === last.next)
            break;
    }
}

// Main function

let last = null;

// Insert a node into the empty list
last = insertInEmptyList(last, 1);

// Print the list
console.log("List after insertion:");
printList(last);

Output
List after insertion: 1 

Time Complexity: O(1)
Auxiliary Space: O(1)

2. Insertion at the beginning in circular linked list

To insert a new node at the beginning of a circular linked list, we first create the new node and allocate memory for it. If the list is empty (indicated by the last pointer being NULL), we make the new node point to itself. If the list already contains nodes then we set the new node’s next pointer to point to the current head of the list (which is last->next), and then update the last node’s next pointer to point to the new node. This maintains the circular structure of the list.

Insertion-at-the-beginning-of-circular-linked-list

Insertion at the beginning in circular linked list

Step-by-step approach:

  • Create a new node with the given value.
  • Check Empty List (last == nullptr):
    • Make newNode->next point to itself.
  • Insert at Beginning:
    • Set newNode->next to last->next.
    • Update last->next to newNode.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;

    Node(int value)
    {
        data = value;
        next = nullptr;
    }
};

// Function to insert a node at the beginning of the
// circular linked list
Node* insertAtBeginning(Node* last, int value){
    // Allocate memory for the new node and set its data
    Node* newNode = new Node(value);

    // If the list is empty, make the new node point to
    // itself and set it as last
    if (last == nullptr) {
        newNode->next = newNode;
        return newNode;
    }

    // Insert the new node at the beginning
    newNode->next = last->next;
    last->next = newNode;

    return last;
}

void printList(Node* last){
  if(last == NULL) return;
  
    // Start from the head node
    Node* head = last->next;
    while (true) {
        cout << head->data << " ";
        head = head->next;
        if (head == last->next)
            break;
    }
    cout << endl;
}

int main(){

    // Create circular linked list: 2, 3, 4
    Node* first = new Node(2);
    first->next = new Node(3);
    first->next->next = new Node(4);

    Node* last = first->next->next;
    last->next = first;

    cout << "Original list: ";
    printList(last);

    // Insert 5 at the beginning
    last = insertAtBeginning(last, 5);

    cout << "List after inserting 5 at the beginning: ";
    printList(last);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Define the Node structure
struct Node
{
    int data;
    struct Node *next;
};

// Function to create a new node
struct Node *createNode(int value)
{
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->next = NULL;
    return newNode;
}

// Function to insert a node at the beginning
// of the circular linked list
struct Node *insertAtBeginning(struct Node *last, int value)
{
    struct Node *newNode = createNode(value);

    // If the list is empty, make the new node point to itself
    // and set it as last
    if (last == NULL)
    {
        newNode->next = newNode;
        return newNode;
    }

    // Insert the new node at the beginning
    newNode->next = last->next;
    last->next = newNode;

    return last;
}

void printList(struct Node *last)
{
    if (last == NULL) return;

    struct Node *head = last->next;
    while (1){
        printf("%d ", head->data);
        head = head->next;
        if (head == last->next)
            break;
    }
    printf("\n");
}

int main()
{
    // Create circular linked list: 2, 3, 4
    struct Node *first = createNode(2);
    first->next = createNode(3);
    first->next->next = createNode(4);
    struct Node *last = first->next->next;
    last->next = first;

    printf("Original list: ");
    printList(last);

    // Insert 5 at the beginning
    last = insertAtBeginning(last, 5);

    printf("List after inserting 5 at the beginning: ");
    printList(last);

    return 0;
}
Java
class Node {
    int data;
    Node next;

    Node(int value){
        data = value;
        next = null;
    }
}

public class GFG {

    // Function to insert a node at the beginning of the
    // circular linked list
    public static Node insertAtBeginning(Node last,
                                         int value){
        Node newNode = new Node(value);

        // If the list is empty, make the new node point to
        // itself and set it as last
        if (last == null) {
            newNode.next = newNode;
            return newNode;
        }

        // Insert the new node at the beginning
        newNode.next = last.next;
        last.next = newNode;

        return last;
    }

    // Function to print the circular linked list
    public static void printList(Node last){
        if (last == null)
            return;

        Node head = last.next;
        while (true) {
            System.out.print(head.data + " ");
            head = head.next;
            if (head == last.next) break;
        }
        System.out.println();
    }

    public static void main(String[] args){
        // Create circular linked list: 2, 3, 4
        Node first = new Node(2);
        first.next = new Node(3);
        first.next.next = new Node(4);
        Node last = first.next.next;
        last.next = first;

        System.out.print("Original list: ");
        printList(last);

        // Insert 5 at the beginning
        last = insertAtBeginning(last, 5);

        System.out.print(
            "List after inserting 5 at the beginning: ");
        printList(last);
    }
}
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# Function to insert a node at the beginning of the circular linked list
def insert_at_beginning(last, value):
    new_node = Node(value)

    # If the list is empty, make the new node point to itself and set it as last
    if last is None:
        new_node.next = new_node
        return new_node

    # Insert the new node at the beginning
    new_node.next = last.next
    last.next = new_node

    return last

# Function to print the circular linked list
def print_list(last):
    if last is None:
        return

    head = last.next
    while True:
        print(head.data, end=" ")
        head = head.next
        if head == last.next:
            break
    print()

# Create circular linked list: 2, 3, 4
first = Node(2)
first.next = Node(3)
first.next.next = Node(4)
last = first.next.next
last.next = first

print("Original list: ", end="")
print_list(last)

# Insert 5 at the beginning
last = insert_at_beginning(last, 5)

print("List after inserting 5 at the beginning: ", end="")
print_list(last)
C#
using System;

public class Node
{
    public int data;
    public Node next;

    public Node(int value)
    {
        data = value;
        next = null;
    }
}

public class CircularLinkedList
{
    // Function to insert a node at the beginning of the circular linked list
    public static Node InsertAtBeginning(Node last, int value)
    {
        Node newNode = new Node(value);

        // If the list is empty, make the new node point to itself and set it as last
        if (last == null)
        {
            newNode.next = newNode;
            return newNode;
        }

        // Insert the new node at the beginning
        newNode.next = last.next;
        last.next = newNode;

        return last;
    }

    // Function to print the circular linked list
    public static void PrintList(Node last)
    {
        if (last == null)
            return;

        Node head = last.next;
        while (true)
        {
            Console.Write(head.data + " ");
            head = head.next;
            if (head == last.next)
                break;
        }
        Console.WriteLine();
    }

    public static void Main(string[] args)
    {
        // Create circular linked list: 2, 3, 4
        Node first = new Node(2);
        first.next = new Node(3);
        first.next.next = new Node(4);
        Node last = first.next.next;
        last.next = first;

        Console.Write("Original list: ");
        PrintList(last);

        // Insert 5 at the beginning
        last = InsertAtBeginning(last, 5);

        Console.Write("List after inserting 5 at the beginning: ");
        PrintList(last);
    }
}
JavaScript
class Node {
    constructor(data)
    {
        this.data = data;
        this.next = null;
    }
}

// Function to insert a node at the beginning of the
// circular linked list
function insertAtBeginning(last, value)
{
    const newNode = new Node(value);

    // If the list is empty, make the new node point to
    // itself and set it as last
    if (last === null) {
        newNode.next = newNode;
        return newNode;
    }

    // Insert the new node at the beginning
    newNode.next = last.next;
    last.next = newNode;

    return last;
}

// Function to print the circular linked list
function printList(last)
{
    if (last === null)
        return;

    let head = last.next;
    while (true) {
        console.log(head.data + " ");
        head = head.next;
        if (head === last.next)
            break;
    }
    console.log();
}

// Create circular linked list: 2, 3, 4
const first = new Node(2);
first.next = new Node(3);
first.next.next = new Node(4);
let last
    = first.next.next; // Using let to allow reassignment
last.next = first;

console.log("Original list: ");
printList(last);

// Insert 5 at the beginning
last = insertAtBeginning(last, 5);

console.log("List after inserting 5 at the beginning: ");
printList(last);

Output
Original list: 2 3 4 
List after inserting 5 at the beginning: 5 2 3 4 

Time Complexity: O(1)
Auxiliary Space: O(1)

3. Insertion at the end in circular linked list

To insert a new node at the end of a circular linked list, we first create the new node and allocate memory for it. If the list is empty (mean, last or tail pointer being NULL), we initialize the list with the new node and making it point to itself to form a circular structure. If the list already contains nodes then we set the new node’s next pointer to point to the current head (which is tail->next), then update the current tail’s next pointer to point to the new node. Finally, we update the tail pointer to the new node. This will ensure that the new node is now the last node in the list while maintaining the circular linkage.

Insertion-at-the-end-of-circular-linked-list

Insertion at the end in circular linked list

Step-by-step approach:

  • Create a new node with the given value.
  • Check Empty List, If last is nullptr then initialize the list with the new node and make it point to itself.
  • Otherwise, Set the new node’s next to the head node.
  • Update the current last’s next to point to the new node.
  • Update last to the new node.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

struct Node{
    int data;
    Node *next;
    Node(int value)
    {
        data = value;
        next = nullptr;
    }
};

// Function to insert a node at the end of a circular linked list
Node *insertEnd(Node *tail, int value)
{
    Node *newNode = new Node(value);
    if (tail == nullptr){
        // If the list is empty, initialize it with the new node
        tail = newNode;

        // Point to itself to form a circular structure
        newNode->next = newNode;
    }
    else{
        // Insert new node after the current tail
        // and update the tail pointer.
        // New node points to the head node
        newNode->next = tail->next;

        // Tail node points to the new node
        tail->next = newNode;

        // Update tail to be the new node
        tail = newNode;
    }
    return tail;
}

void printList(Node *last){
  if(last == NULL) return;
  
    // Start from the head node
    Node *head = last->next;
    while (true){
        cout << head->data << " ";
        head = head->next;
        if (head == last->next)
            break;
    }
    cout << endl;
}

int main(){
    // Create circular linked list: 2, 3, 4
    Node *first = new Node(2);
    first->next = new Node(3);
    first->next->next = new Node(4);

    Node *last = first->next->next;
    last->next = first;

    cout << "Original list: ";
    printList(last);

    // Insert elements at the end of the circular linked list
    last = insertEnd(last, 5);
    last = insertEnd(last, 6);

    cout << "List after inserting 5 and 6: ";
    printList(last);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Define the Node structure
struct Node
{
    int data;
    struct Node *next;
};

// Function to create a new node
struct Node *createNode(int value);

// Function to insert a node at the end of a circular linked list
struct Node *insertEnd(struct Node *tail, int value)
{
    struct Node *newNode = createNode(value);
    if (tail == NULL)
    {
        // If the list is empty, initialize it with the new node
        tail = newNode;
        newNode->next = newNode;
    }
    else
    {
        // Insert new node after the current tail and update the tail pointer
        newNode->next = tail->next;
        tail->next = newNode;
        tail = newNode;
    }
    return tail;
}

// Function to print the circular linked list
void printList(struct Node *last)
{
    if (last == NULL)
        return;

    struct Node *head = last->next;
    while (1)
    {
        printf("%d ", head->data);
        head = head->next;
        if (head == last->next)
            break;
    }
    printf("\n");
}

struct Node *createNode(int value)
{
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->next = NULL;
    return newNode;
}

int main()
{
    // Create circular linked list: 2, 3, 4
    struct Node *first = createNode(2);
    first->next = createNode(3);
    first->next->next = createNode(4);

    struct Node *last = first->next->next;
    last->next = first;

    printf("Original list: ");
    printList(last);

    // Insert elements at the end of the circular linked list
    last = insertEnd(last, 5);
    last = insertEnd(last, 6);

    printf("List after inserting 5 and 6: ");
    printList(last);

    return 0;
}
Java
class Node {
    int data;
    Node next;

    Node(int value){
        data = value;
        next = null;
    }
}

public class GFG {

    // Function to insert a node at the end of a circular
    // linked list
    static Node insertEnd(Node tail, int value){
        Node newNode = new Node(value);
        if (tail == null) {
            // If the list is empty, initialize it with the
            // new node
            tail = newNode;
            newNode.next = newNode;
        }
        else {
            // Insert new node after the current tail and
            // update the tail pointer
            newNode.next = tail.next;
            tail.next = newNode;
            tail = newNode;
        }
        return tail;
    }

    // Function to print the circular linked list
    static void printList(Node last){
        if (last == null) return;

        Node head = last.next;
        while (true) {
            System.out.print(head.data + " ");
            head = head.next;
            if (head == last.next) break;
        }
        System.out.println();
    }

    public static void main(String[] args){
        // Create circular linked list: 2, 3, 4
        Node first = new Node(2);
        first.next = new Node(3);
        first.next.next = new Node(4);

        Node last = first.next.next;
        last.next = first;

        System.out.print("Original list: ");
        printList(last);

        // Insert elements at the end of the circular linked
        // list
        last = insertEnd(last, 5);
        last = insertEnd(last, 6);

        System.out.print("List after inserting 5 and 6: ");
        printList(last);
    }
}
Python
class Node:
    def __init__(self, value):
        self.data = value
        self.next = None

# Function to insert a node at the end of a circular linked list


def insert_end(tail, value):
    new_node = Node(value)
    if tail is None:
        # If the list is empty, initialize
        # it with the new node
        tail = new_node
        new_node.next = new_node
    else:
        # Insert new node after the current tail
        # and update the tail pointer
        new_node.next = tail.next
        tail.next = new_node
        tail = new_node
    return tail

# Function to print the circular linked list


def print_list(last):
    if last is None:
        return

    head = last.next
    while True:
        print(head.data, end=" ")
        head = head.next
        if head == last.next:
            break
    print()


if __name__ == "__main__":
    # Create circular linked list: 2, 3, 4
    first = Node(2)
    first.next = Node(3)
    first.next.next = Node(4)

    last = first.next.next
    last.next = first

    print("Original list: ", end="")
    print_list(last)

    # Insert elements at the end of the circular linked list
    last = insert_end(last, 5)
    last = insert_end(last, 6)

    print("List after inserting 5 and 6: ", end="")
    print_list(last)
JavaScript
class Node {
    constructor(value){
        this.data = value;
        this.next = null;
    }
}

// Function to insert a node at the end of a circular linked
// list
function insertEnd(tail, value){
    let newNode = new Node(value);
    if (tail === null) {
        // If the list is empty, initialize it with the new
        // node
        tail = newNode;
        newNode.next = newNode;
    }
    else {
        // Insert new node after the current tail and update
        // the tail pointer
        newNode.next = tail.next;
        tail.next = newNode;
        tail = newNode;
    }
    return tail;
}

// Function to print the circular linked list
function printList(last)
{
    if (last === null)
        return;

    let head = last.next;
    while (true) {
        console.log(head.data + " ");
        head = head.next;
        if (head === last.next)
            break;
    }
    console.log();
}

// Create circular linked list: 2, 3, 4
let first = new Node(2);
first.next = new Node(3);
first.next.next = new Node(4);

let last = first.next.next;
last.next = first;

console.log("Original list: ");
printList(last);

// Insert elements at the end of the circular linked
// list
last = insertEnd(last, 5);
last = insertEnd(last, 6);

console.log("List after inserting 5 and 6: ");
printList(last);

Output
Original list: 2 3 4 
List after inserting 5 and 6: 2 3 4 5 6 

Time Complexity: O(1)
Auxiliary Space: O(1)

4. Insertion at specific position in circular linked list

To insert a new node at a specific position in a circular linked list, we first check if the list is empty. If it is and the position is not 1 then we print an error message because the position doesn’t exist in the list. If the position is 1 then we create the new node and make it point to itself. If the list is not empty, we create the new node and traverse the list to find the correct insertion point. If the position is 1, we insert the new node at the beginning by adjusting the pointers accordingly. For other positions, we traverse through the list until we reach the desired position and inserting the new node by updating the pointers. If the new node is inserted at the end, we also update the last pointer to reference the new node, maintaining the circular structure of the list.

Insertion-at-specific-position-of-circular-linked-list

Insertion at specific position in circular linked list

Step-by-step approach:

  • If last is nullptr and pos is not 1, print “Invalid position!“.
  • Otherwise, Create a new Node with given data.
  • Insert at Beginning: If pos is 1, update pointers and return last.
  • Traverse List: Loop to find the insertion point; print “Invalid position!” if out of bounds.
  • Insert Node: Update pointers to insert the new node.
  • Update Last: If inserted at the end, update last.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

struct Node{
    int data;
    Node *next;
    Node(int value){
        data = value;
        next = nullptr;
    }
};

// Function to insert a node at a specific position in a circular linked list
Node *insertAtPosition(Node *last, int data, int pos){
    if (last == nullptr){
        // If the list is empty
        if (pos != 1){
            cout << "Invalid position!" << endl;
            return last;
        }
        // Create a new node and make it point to itself
        Node *newNode = new Node(data);
        last = newNode;
        last->next = last;
        return last;
    }

    // Create a new node with the given data
    Node *newNode = new Node(data);

    // curr will point to head initially
    Node *curr = last->next;

    if (pos == 1){
        // Insert at the beginning
        newNode->next = curr;
        last->next = newNode;
        return last;
    }

    // Traverse the list to find the insertion point
    for (int i = 1; i < pos - 1; ++i) {
        curr = curr->next;
      
        // If position is out of bounds
        if (curr == last->next){
            cout << "Invalid position!" << endl;
            return last;
        }
    }
    // Insert the new node at the desired position
    newNode->next = curr->next;
    curr->next = newNode;

    // Update last if the new node is inserted at the end
    if (curr == last) last = newNode;

    return last;
}

void printList(Node *last){
    if (last == NULL) return;

    Node *head = last->next;
    while (true){
        cout << head->data << " ";
        head = head->next;
        if (head == last->next) break;
    }
    cout << endl;
}

int main(){
    // Create circular linked list: 2, 3, 4
    Node *first = new Node(2);
    first->next = new Node(3);
    first->next->next = new Node(4);

    Node *last = first->next->next;
    last->next = first;

    cout << "Original list: ";
    printList(last);

    // Insert elements at specific positions
    int data = 5, pos = 2;
    last = insertAtPosition(last, data, pos);
    cout << "List after insertions: ";
    printList(last);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Define the Node structure
struct Node {
    int data;
    struct Node *next;
};

struct Node* createNode(int value);

// Function to insert a node at a specific position in a circular linked list
struct Node* insertAtPosition(struct Node *last, int data, int pos) {
    if (last == NULL) {
        // If the list is empty
        if (pos != 1) {
            printf("Invalid position!\n");
            return last;
        }
        // Create a new node and make it point to itself
        struct Node *newNode = createNode(data);
        last = newNode;
        last->next = last;
        return last;
    }

    // Create a new node with the given data
    struct Node *newNode = createNode(data);

    // curr will point to head initially
    struct Node *curr = last->next;

    if (pos == 1) {
        // Insert at the beginning
        newNode->next = curr;
        last->next = newNode;
        return last;
    }

    // Traverse the list to find the insertion point
    for (int i = 1; i < pos - 1; ++i) {
        curr = curr->next;

        // If position is out of bounds
        if (curr == last->next) {
            printf("Invalid position!\n");
            return last;
        }
    }

    // Insert the new node at the desired position
    newNode->next = curr->next;
    curr->next = newNode;

    // Update last if the new node is inserted at the end
    if (curr == last) last = newNode;

    return last;
}

// Function to print the circular linked list
void printList(struct Node *last) {
    if (last == NULL) return;

    struct Node *head = last->next;
    while (1) {
        printf("%d ", head->data);
        head = head->next;
        if (head == last->next) break;
    }
    printf("\n");
}

// Function to create a new node
struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->next = NULL;
    return newNode;
}

int main() {
    // Create circular linked list: 2, 3, 4
    struct Node *first = createNode(2);
    first->next = createNode(3);
    first->next->next = createNode(4);

    struct Node *last = first->next->next;
    last->next = first;

    printf("Original list: ");
    printList(last);

    // Insert elements at specific positions
    int data = 5, pos = 2;
    last = insertAtPosition(last, data, pos);
    printf("List after insertions: ");
    printList(last);

    return 0;
}
Java
class Node {
    int data;
    Node next;

    Node(int value){
        data = value;
        next = null;
    }
}

public class GFG {

    // Function to insert a node at a specific position in a
    // circular linked list
    static Node insertAtPosition(Node last, int data,
                                 int pos){
        if (last == null) {
            // If the list is empty
            if (pos != 1) {
                System.out.println("Invalid position!");
                return last;
            }
            // Create a new node and make it point to itself
            Node newNode = new Node(data);
            last = newNode;
            last.next = last;
            return last;
        }

        // Create a new node with the given data
        Node newNode = new Node(data);

        // curr will point to head initially
        Node curr = last.next;

        if (pos == 1) {
            // Insert at the beginning
            newNode.next = curr;
            last.next = newNode;
            return last;
        }

        // Traverse the list to find the insertion point
        for (int i = 1; i < pos - 1; ++i) {
            curr = curr.next;

            // If position is out of bounds
            if (curr == last.next) {
                System.out.println("Invalid position!");
                return last;
            }
        }

        // Insert the new node at the desired position
        newNode.next = curr.next;
        curr.next = newNode;

        // Update last if the new node is inserted at the
        // end
        if (curr == last)
            last = newNode;

        return last;
    }

    static void printList(Node last){
        if (last == null)
            return;

        Node head = last.next;
        while (true) {
            System.out.print(head.data + " ");
            head = head.next;
            if (head == last.next)
                break;
        }
        System.out.println();
    }

    public static void main(String[] args)
    {
        // Create circular linked list: 2, 3, 4
        Node first = new Node(2);
        first.next = new Node(3);
        first.next.next = new Node(4);

        Node last = first.next.next;
        last.next = first;

        System.out.print("Original list: ");
        printList(last);

        // Insert elements at specific positions
        int data = 5, pos = 2;
        last = insertAtPosition(last, data, pos);
        System.out.print("List after insertions: ");
        printList(last);
    }
}
Python
class Node:
    def __init__(self, value):
        self.data = value
        self.next = None

# Function to insert a node at a specific position in a circular linked list
def insertAtPosition(last, data, pos):
    if last is None:
        # If the list is empty
        if pos != 1:
            print("Invalid position!")
            return last
        # Create a new node and make it point to itself
        new_node = Node(data)
        last = new_node
        last.next = last
        return last

    # Create a new node with the given data
    new_node = Node(data)

    # curr will point to head initially
    curr = last.next

    if pos == 1:
        # Insert at the beginning
        new_node.next = curr
        last.next = new_node
        return last

    # Traverse the list to find the insertion point
    for i in range(1, pos - 1):
        curr = curr.next

        # If position is out of bounds
        if curr == last.next:
            print("Invalid position!")
            return last

    # Insert the new node at the desired position
    new_node.next = curr.next
    curr.next = new_node

    # Update last if the new node is inserted at the end
    if curr == last:
        last = new_node

    return last

# Function to print the circular linked list
def print_list(last):
    if last is None:
        return

    head = last.next
    while True:
        print(head.data, end=" ")
        head = head.next
        if head == last.next:
            break
    print()

if __name__ == "__main__":
    # Create circular linked list: 2, 3, 4
    first = Node(2)
    first.next = Node(3)
    first.next.next = Node(4)

    last = first.next.next
    last.next = first

    print("Original list: ", end="")
    print_list(last)

    # Insert elements at specific positions
    data = 5
    pos = 2
    last = insertAtPosition(last, data, pos)
    print("List after insertions: ", end="")
    print_list(last)
JavaScript
class Node {
    constructor(value){
        this.data = value;
        this.next = null;
    }
}

// Function to insert a node at a specific position in a
// circular linked list
function insertAtPosition(last, data, pos)
{
    if (last === null) {
        // If the list is empty
        if (pos !== 1) {
            console.log("Invalid position!");
            return last;
        }
        // Create a new node and make it point to itself
        let newNode = new Node(data);
        last = newNode;
        last.next = last;
        return last;
    }

    // Create a new node with the given data
    let newNode = new Node(data);

    // curr will point to head initially
    let curr = last.next;

    if (pos === 1) {
        // Insert at the beginning
        newNode.next = curr;
        last.next = newNode;
        return last;
    }

    // Traverse the list to find the insertion point
    for (let i = 1; i < pos - 1; ++i) {
        curr = curr.next;

        // If position is out of bounds
        if (curr === last.next) {
            console.log("Invalid position!");
            return last;
        }
    }

    // Insert the new node at the desired position
    newNode.next = curr.next;
    curr.next = newNode;

    // Update last if the new node is inserted at the end
    if (curr === last)
        last = newNode;

    return last;
}

// Function to print the circular linked list
function printList(last){
    if (last === null)
        return;

    let head = last.next;
    while (true) {
        console.log(head.data + " ");
        head = head.next;
        if (head === last.next)
            break;
    }
    console.log();
}

// Create circular linked list: 2, 3, 4
let first = new Node(2);
first.next = new Node(3);
first.next.next = new Node(4);

let last = first.next.next;
last.next = first;

console.log("Original list: ");
printList(last);

// Insert elements at specific positions
let data = 5;
let pos = 2;
last = insertAtPosition(last, data, pos);
console.log("List after insertions: ");
printList(last);

Output
Original list: 2 3 4 
List after insertions: 2 5 3 4 

Time Complexity: O(n), we have to traverse the list to find the specific position.
Auxiliary Space: O(1)




Similar Reads

Convert singly linked list into circular linked list
Given a singly linked list, we have to convert it into circular linked list. For example, we have been given a singly linked list with four nodes and we want to convert this singly linked list into circular linked list. Approach: The idea is to traverse the singly linked list and check if the node is the last node or not. If the node is the last no
14 min read
Insertion in an empty List in the circular linked list
A circular linked list is a type of data structure where each node points to the next one, and the last node connects back to the first, forming a circle. This setup allows you to loop through the list without stopping. Knowing how to insert a node into an empty circular linked list is important in creating circular linked list. Insertion in an emp
5 min read
Javascript Program For Insertion Sort In A Singly Linked List
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert current node in sorted way in sorted or result list. 3
3 min read
Insertion Sort for Singly Linked List
We have discussed Insertion Sort for arrays. In this article, we are going to discuss Insertion Sort for a linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list 2) Traverse the given list, do following for every node. ......a) Insert current node in sorted way in sorted or result list.
11 min read
Insertion in a sorted circular linked list when a random pointer is given
Given an array arr[] of integers and a pointer to a random node of a circular sorted linked list (initially empty), the task is to insert all the elements of arr[] into the circular linked list. Examples: Input: arr[] = {12, 56, 2, 11, 1, 90} Output: 1 2 11 12 56 90 Input: arr[] = {6, 2, 78, 45, 200} Output: 2 6 45 78 200 Approach: We are given a r
12 min read
Insertion at Specific Position in a Circular Doubly Linked List
Prerequisite: Insert Element Circular Doubly Linked List.Convert an Array to a Circular Doubly Linked List.Given the start pointer pointing to the start of a Circular Doubly Linked List, an element and a position. The task is to insert the element at the specified position in the given Circular Doubly Linked List. Recommended: Please try your appro
15+ min read
Insertion in Doubly Circular Linked List
Circular Doubly Linked List has properties of both doubly linked list and circular linked list in which two consecutive elements are linked or connected by the previous and next pointer and the last node points to the first node by the next pointer and also the first node points to the last node by the previous pointer. Following is the representat
15+ min read
Insertion at the beginning in circular linked list
A circular linked list is a special type of data structure where each node points to the next, and the last node connects back to the first, forming a loop. This design allows for continuous traversal without stopping. Inserting a node at the beginning of a circular linked list is an important operation, especially when starting with an empty list.
7 min read
Insertion at the end in circular linked list
A circular linked list is a data structure where each node points to the next, and the last node connects back to the first, creating a loop. Insertion at the end in circular linked list is an important operation. Understanding how to perform this insertion is essential for effectively manage and use circular linked lists in various applications. I
7 min read
Delete all Prime Nodes from a Circular Singly Linked List
Given a circular singly linked list containing N nodes. The task is to delete all nodes from the list which are prime. Examples: Input : 9-&gt;11-&gt;32-&gt;6-&gt;13-&gt;20 Output : 9 32 6 20 Input : 6-&gt;11-&gt;16-&gt;21-&gt;17-&gt;10 Output : 6 16 21 10 Approach: The idea is to traverse the nodes of the circular singly linked list one by one and
13 min read
Find minimum and maximum elements in singly Circular Linked List
Given a singly circular linked list of [Tex]N [/Tex]nodes. The task is to find the smallest and largest elements in the circular linked list. Examples: Input : List = 99-&gt;11-&gt;22-&gt;33-&gt;44-&gt;55-&gt;66 Output : Minimum = 11, Maximum = 99 Input : List = 12-&gt;11-&gt;9-&gt;33-&gt;125-&gt;6-&gt;99 Output : Minimum = 6, Maximum = 125 The ide
14 min read
Sum and Product of the nodes of a Circular Singly Linked List which are divisible by K
Given a singly circular linked list. The task is to find the sum and product of nodes that are divisible by K of the given linked list. Examples: Input : List = 5-&gt;6-&gt;7-&gt;8-&gt;9-&gt;10-&gt;11-&gt;11 K = 11 Output : Sum = 22, Product = 121 Input : List = 15-&gt;7-&gt;3-&gt;9-&gt;11-&gt;5 K = 5 Output : Product = 75, Sum = 20 Approach: Initi
12 min read
Remove all Fibonacci Nodes from a Circular Singly Linked List
Given a circular singly linked list containing N nodes, the task is to remove all the nodes from the list which contains Fibonacci data values.Examples: Input: CLL = 9 -&gt; 11 -&gt; 34 -&gt; 6 -&gt; 13 -&gt; 20 Output: 9 -&gt; 11 -&gt; 6 -&gt; 20 Explanation: The list contains 2 fibonacci data values 32 and 13. Therefore, the nodes containing this
15+ min read
Remove all the Even Digit Sum Nodes from a Circular Singly Linked List
Given a circular singly linked list containing N nodes, the task is to remove all the nodes from the list which contains elements whose digit sum is even. Examples: Input: CLL = 9 -&gt; 11 -&gt; 34 -&gt; 6 -&gt; 13 -&gt; 21 Output: 9 -&gt; 34 -&gt; 21 Explanation: The circular singly linked list contains : 9 -&gt; 9 11 -&gt; 1 + 1 = 2 34 -&gt; 3 +
12 min read
Remove all even parity nodes from a Doubly and Circular Singly Linked List
Given a Doubly linked list and Circular singly linked list containing N nodes, the task is to remove all the nodes from each list which contains elements whose parity is even. Example: Input: CLL = 9 -&gt; 11 -&gt; 34 -&gt; 6 -&gt; 13 -&gt; 21 Output: 11 -&gt; 13 -&gt; 21 Explanation: The circular singly linked list contains : 11 -&gt; 1011, parity
15+ min read
Convert Singly Linked List to XOR Linked List
Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a singly linked list, the task is to convert the gi
9 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node.  Introduction to Doubly linked list : A Doubly Linked List (
2 min read
Circular Linked List Implementation of Circular Queue
Prerequisite – Circular Singly Linked List We have discussed basics and how to implement circular queue using array in set 1. Circular Queue | Set 1 (Introduction and Array Implementation) In this post another method of circular queue implementation is discussed, using Circular Singly Linked List. Operations on Circular Queue: Front:Get the front i
9 min read
Check if a linked list is Circular Linked List
Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node. Note: The linked list does not contain any internal loops. Example: Input: LinkedList: 2-&gt;4-&gt;6-&gt;7-&gt;5 Output: trueExplanation: As shown in figure the first a
12 min read
Insertion in Unrolled Linked List
An unrolled linked list is a linked list of small arrays, all of the same size where each is so small that the insertion or deletion is fast and quick, but large enough to fill the cache line. An iterator pointing into the list consists of both a pointer to a node and an index into that node containing an array. It is also a data structure and is a
11 min read
Insertion Sort for Doubly Linked List
Sort the doubly linked list using the insertion sort technique. Initial doubly linked list Doubly Linked List after applying insertion sort Algorithm: Below is a simple insertion sort algorithm for doubly-linked lists.1) Create an empty sorted (or result) doubly linked list. 2) Traverse the given doubly linked list, and do the following for every n
14 min read
Recursive insertion and traversal linked list
We have discussed different methods of linked list insertion. How to recursively create a linked list? Recursively inserting at the end: To create a Linked list using recursion follow these steps. Below steps insert a new node recursively at the end of linked list. C/C++ Code // Function to insert a new node at the // end of linked list using recur
9 min read
Insertion in a Doubly Linked List
Inserting a new node in a doubly linked list is very similar to inserting new node in linked list. There is a little extra work required to maintain the link of the previous node. In this article, we will learn about different ways to insert a node in a doubly linked list. Table of Content Insertion at the Beginning in Doubly Linked ListInsertion a
15+ min read
Insertion in Linked List
Given a Linked List, the task is to insert a new node in this given Linked List at the following positions:  At the front of the linked list  After a given node.At a specific position.At the end of the linked list.Insert a Node at the Front/Beginning of Linked ListTo insert a new node at the front, we create a new node and point its next reference
15+ min read
Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
A simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires a pointer to the head node which contradicts the problem statement. The fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like this: It is important to note that thi
7 min read
Reverse alternate K nodes in a Singly Linked List
Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;9-&gt;NULL and k = 3 Output: 3-&gt;2-&gt;1-&gt;4-&gt;5-&gt;6-&gt;9-&gt;8-&gt;7-&gt;NULL. Method 1 (Process 2k node
15+ min read
Select a Random Node from a Singly Linked List
Given a singly linked list, select a random node from the linked list (the probability of picking a node should be 1/N if there are N nodes in the list). You are given a random number generator.Below is a Simple Solution Count the number of nodes by traversing the list. Traverse the list again and select every node with a probability of 1/N. The se
15 min read
Alternate Odd and Even Nodes in a Singly Linked List
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even an
15+ min read
Find middle of singly linked list Recursively
Given a singly linked list and the task is to find the middle of the linked list. Examples: Input : 1-&gt;2-&gt;3-&gt;4-&gt;5 Output : 3 Input : 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6 Output : 4 We have already discussed Iterative Solution. In this post iterative solution is discussed. Count total number of nodes in the list in recursive manner and do hal
5 min read