Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Insertion in an empty List in the circular linked list
Next article icon

Insertion at the end in circular linked list

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

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)


Next Article
Insertion in an empty List in the circular linked list

H

harendrakumar123
Improve
Article Tags :
  • Linked List
  • Data Structures
  • DSA
  • circular linked list
Practice Tags :
  • circular linked list
  • Data Structures
  • Linked List

Similar Reads

  • 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
    5 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 opera
    7 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
    15+ min read
  • Insertion in Circular Singly Linked List
    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 ad
    12 min read
  • Insertion at specific position in circular linked list
    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 pro
    10 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 Doub
    15+ min read
  • Sorted insert for circular linked list
    Given a sorted Circular Linked List. The task is to insert the given data in a sorted way. Examples: Input: Output: Explanation: 8 is inserted after 7 and before 9 to preserve the sorted order. Input: Output: Explanation: 1 will be inserted at the beginning of circular linked list. Approach: To inse
    10 min read
  • Introduction to Circular Linked List
    A circular linked list is a data structure where the last node connects back to the first, forming a loop. This structure allows for continuous traversal without any interruptions. Circular linked lists are especially helpful for tasks like scheduling and managing playlists, allowing for smooth navi
    15+ 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
    6 min read
  • Introduction to Circular Doubly Linked List
    A circular doubly linked list is defined as a circular linked list in which each node has two links connecting it to the previous node and the next node. Characteristics of Circular Doubly Linked List :A circular doubly linked list has the following properties: Circular: A circular doubly linked lis
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences