Insertion in Circular Singly Linked List
Last Updated :
24 Feb, 2025
In this article, we will learn how to insert a node into a circular linked list. Insertion is a fundamental operation in linked lists that involves adding a new node to the 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 a specific position in the list
Advantages of using a tail pointer instead of a head pointer
We need to traverse the whole list to insert a node at the beginning. 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 the end takes constant time, irrespective of the length of the list.
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 ListStep-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.
To read more about insertion in an empty list Refer: Insertion in an empty List in the circular linked list
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),
- 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 in circular linked listTo read more about Insertion in the beginning Refer: Insertion at the beginning in circular linked list
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 in circular linked listTo read more about Insertion at the end Refer: Insertion at the end in circular linked list
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. I
- f 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 in circular linked listStep-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.
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);
OutputOriginal 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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem