Open In App

Insertion at specific position in circular linked list

Last Updated : 24 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Inserting an element at a specific position in a circular linked list is a common operation that involves adjusting pointers in a circular structure. Unlike a regular linked list, where the last node points to NULL, a circular linked list’s last node points back to the head, forming a loop. This property makes insertion at various positions, including the beginning, middle, and end, slightly different compared to a linear linked list.

Examples:

Input: data = 5, pos = 2
Output: Original list: 2 3 4
List after insertions: 2 5 3 4
Explanation: The new node with data 5 is inserted at position 2. The list becomes 2 -> 5 -> 3 -> 4.

Input: data = 1, pos = 1
Output: Original list: 2 3 4
List after insertions: 1 2 3 4
Explanation: The new node with data 1 is inserted at the beginning (position 1). The list becomes 1 -> 2 -> 3 -> 4.

Input: data = 6, pos = 5
Output: Original list: 2 3 4
List after insertions: Invalid position!
Explanation: The position 5 is invalid because the list has only 3 elements. Therefore, no insertion is made, and the list remains unchanged.

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

Steps for Insertion at a Specific Position in a Circular Linked List

  • Check if the list is empty
    • If the position is not 1, print an error message (since the position doesn’t exist in an empty list).
    • If the position is 1, create the new node and make its next pointer point to itself (since it is the only node).
  • If the list is not empty: Create the new node with the given data.
  • For insertion at position 1 (insert at the beginning):
    • Traverse the list to find the last node (the node whose next pointer points to the head).
    • Set the new node’s next pointer to the current head.
    • Set the next pointer of the last node to the new node.
    • Update the head to point to the new node.
  • For insertion at positions other than 1
    • Traverse the list to reach the node just before the desired position (position - 1).
    • Once you reach that node, set the new node’s next pointer to point to the node that was previously at the desired position.
    • Set the (position-1)-th node’s next pointer to the new node.
  • If the new node is inserted at the end
    • Update the last node’s next pointer to point to the new node, maintaining the circular nature of the list.
    • Ensure the new node’s next pointer points to the head, completing the circle.
    • This process ensures that the circular structure of the linked list is preserved after every insertion.
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>

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 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;
}

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 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 CircularLinkedList {
    
    // Function to insert a node at a specific position in a circular linked list
    public 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 (beyond the circular linked list)
            if (curr == last) {
                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;
    }

    // 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 -> (back to 2)
        Node first = new Node(2);
        first.next = new Node(3);
        first.next.next = new Node(4);
        first.next.next.next = first; 

        Node last = first.next.next; 
        System.out.print("Original list: ");
        printList(last);

        // Insert element at position 2
        int data = 5, pos = 2;
        last = insertAtPosition(last, data, pos);
        System.out.print("List after insertion: ");
        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 insert_at_position(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

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 = insert_at_position(last, data, pos)
    print("List after insertions:", end=' ')
    print_list(last)
JavaScript
// Node structure
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 printList(last) {
    if (last === null) return;
    let head = last.next;
    while (true) {
        console.log(head.data);
        head = head.next;
        if (head === last.next) break;
    }
}

// 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, 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)


Next Article
Article Tags :
Practice Tags :

Similar Reads