Open In App

Insertion in Doubly Circular Linked List

Last Updated : 16 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. In this article, we will learn about different ways to insert a node in a doubly circular linked list.

Insertion at the Beginning in Doubly Circular Linked List – O(1) Time and O(1) Space:

To insert a new node at the front of a doubly circular linked list,

  • Allocate memory for the new node.
  • If the list is empty, set the new node’s next and prev to point to itself, and update the head to this new node.
  • For a non-empty list, insert the new node:
    • Set the new node’s next to the current head.
    • Set the new node’s prev to the last node.
    • Update the current head’s prev to the new node.
    • Update the last node’s next to the new node.
  • Set the new node as the new head of the list.
C++
// C++ code of insert node at begin in 
// doubly Circular linked list.
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node* prev;
    
    Node(int x) {
        data = x;
          next = nullptr;
          prev = nullptr;
    }
};


// Function to insert a node at the 
// beginning of the doubly circular linked list
Node* insertAtBeginning(Node* head, int newData) {
  
    Node* newNode = new Node(newData);
    
    if (!head) {
        newNode->next = newNode->prev = newNode;
        head = newNode;
    } else {
      
        // List is not empty
          // Last node in the list
        Node* last = head->prev; 

        // Insert new node
        newNode->next = head;
        newNode->prev = last;
        head->prev = newNode;
        last->next = newNode;
        
        // Update head
        head = newNode;
    }
    
    return head;
}

void printList(Node* head) {
    if (!head) return;
    Node* curr = head;
    do {
        cout << curr->data << " ";
        curr = curr->next;
    } while (curr != head);
    cout << endl;
}

int main() {
  
    // Linked List : 10<->20<->30
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->prev = head;
    head->next->next = new Node(30);
    head->next->next->prev = head->next;
    head->next->next->next = head;
    head->prev = head->next->next;

    head = insertAtBeginning(head, 5);
    printList(head);

    return 0;
}
C
// C code of insert node at begin in 
// doubly Circular linked list.

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

struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
};


struct Node* createNode(int x);

// Function to insert a node at the 
// beginning of the doubly circular linked list
struct Node* insertAtBeginning(struct Node* head, int newData) {
  
    struct Node* newNode = createNode(newData);
    
    if (!head) {
        newNode->next = newNode->prev = newNode;
        head = newNode;
    } else {
      
        // List is not empty
        struct Node* last = head->prev; 

        // Insert new node
        newNode->next = head;
        newNode->prev = last;
        head->prev = newNode;
        last->next = newNode;
        
        // Update head
        head = newNode;
    }
    
    return head;
}

void printList(struct Node* head) {
    if (!head) return;
    struct Node* curr = head;
    do {
        printf("%d ", curr->data);
        curr = curr->next;
    } while (curr != head);
    printf("\n");
}

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

int main(){
  
    // Linked List : 10<->20<->30
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->prev = head;
    head->next->next = createNode(30);
    head->next->next->prev = head->next;
    head->next->next->next = head;
    head->prev = head->next->next;


    head = insertAtBeginning(head, 5);
    printList(head);

    return 0;
}
Java
// Java code of insert node at begin in 
// doubly Circular linked list.

class Node {
    int data;
    Node next;
    Node prev;

    Node(int x) {
        data = x;
        next = null;
          prev = null;
    }
}

class GfG {

    // Function to insert a node at the beginning
      // of the doubly circular linked list
       static Node insertAtBeginning(Node head, int newData) {
        Node newNode = new Node(newData);
        
        if (head == null) {
          
            // List is empty
            newNode.next = newNode.prev = newNode;
            head = newNode;
        } else {
          
            // List is not empty
            Node last = head.prev;

            // Insert new node
            newNode.next = head;
            newNode.prev = last;
            head.prev = newNode;
            last.next = newNode;
            
            // Update head
            head = newNode;
        }
        
        return head;
    }

    static void printList(Node head) {
        if (head == null) return;
        Node curr = head;
        do {
            System.out.print(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        System.out.println();
    }

    public static void main(String[] args) {
      
        // Linked List : 10<->20<->30
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.prev = head;
        head.next.next = new Node(30);
        head.next.next.prev = head.next;
        head.next.next.next = head;
        head.prev = head.next.next;

        head = insertAtBeginning(head, 5);
        printList(head);
    }
}
Python
# Python code of insert node at begin in 
# doubly Circular linked list.

class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
        self.prev = None

def insertAtBeginning(head, newData):
    newNode = Node(newData)
    
    if head is None:
      
        # List is empty
        newNode.next = newNode.prev = newNode
        head = newNode
    else:
      
        # List is not empty
        last = head.prev 

        # Insert new node
        newNode.next = head
        newNode.prev = last
        head.prev = newNode
        last.next = newNode
        
        # Update head
        head = newNode
    
    return head

def printList(head):
    if not head:
        return
    curr = head
    while True:
        print(curr.data, end=" ")
        curr = curr.next
        if curr == head:
            break
    print()

# Linked List : 10<->20<->30
head = Node(10)
head.next = Node(20)
head.next.prev = head
head.next.next = Node(30)
head.next.next.prev = head.next
head.next.next.next = head
head.prev = head.next.next

head = insertAtBeginning(head, 5)
printList(head)
C#
// C# code of insert node at begin in 
// doubly Circular linked list.
using System;

class Node {
    public int Data;
    public Node next;
    public Node prev;

    public Node(int x) {
        Data = x;
        next = null;
        prev = null;
    }
}

class GfG {

    // Function to insert a node at the 
    // beginning of the doubly circular linked list
    static Node InsertAtBeginning(Node head, int newData) {
        Node newNode = new Node(newData);
        
        if (head == null) {
          
            // List is empty
            newNode.next = newNode.prev = newNode;
            head = newNode;
        } else {
          
            // List is not empty
            Node last = head.prev;

            // Insert new node
            newNode.next = head;
            newNode.prev = last;
            head.prev = newNode;
            last.next = newNode;
            
            // Update head
            head = newNode;
        }
        
        return head;
    }
  
    static void PrintList(Node head) {
        if (head == null) return;
        Node curr = head;
        do {
            Console.Write(curr.Data + " ");
            curr = curr.next;
        } while (curr != head);
        Console.WriteLine();
    }

    static void Main() {
      
        // Linked List : 10<->20<->30
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.prev = head;
        head.next.next = new Node(30);
        head.next.next.prev = head.next;
        head.next.next.next = head;
        head.prev = head.next.next;
      
        head = InsertAtBeginning(head, 5);
        PrintList(head);
    }
}
JavaScript
// Javascript code of insert node at begin in 
// doubly Circular linked list.

class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
        this.prev = null;
    }
}

function insertAtBeginning(head, newData) {
    let newNode = new Node(newData);
    
    if (!head) {
    
        // List is empty
        newNode.next = newNode.prev = newNode;
        head = newNode;
    } else {
    
        // List is not empty
        let last = head.prev;

        // Insert new node
        newNode.next = head;
        newNode.prev = last;
        head.prev = newNode;
        last.next = newNode;
        
        // Update head
        head = newNode;
    }
    
    return head;
}

function printList(head) {
    if (!head) return;
    let curr = head;
    do {
        console.log(curr.data + " ");
        curr = curr.next;
    } while (curr !== head);
    console.log();
}

// Linked List : 10<->20<->30
let head = new Node(10);
head.next = new Node(20);
head.next.prev = head;
head.next.next = new Node(30);
head.next.next.prev = head.next;
head.next.next.next = head;
head.prev = head.next.next;

head = insertAtBeginning(head, 5);
printList(head);

Output
5 10 20 30 

Time Complexity: O(1), Since we are not traversing the list.
Auxiliary Space: O(1)

Insertion at the End in Doubly Circular Linked List – O(1) Time and O(1) Space:

To insert a new node at the end of doubly circular linked list,

  • Allocate memory for the new node.
  • If the list is empty, set the new node’s next and prev pointers to point to itself, and update the head to this new node.
  • For a non-empty list, insert the new node:
    • Find the current last node (the node whose next pointer points to the head).
    • Set the new node’s next pointer to point to the head.
    • Set the new node’s prev pointer to point to the current last node.
    • Update the current last node’s next pointer to point to the new node.
    • Update the head’s prev pointer to point to the new node.
C++
// C++ code of insert node at End in 
// doubly Circular linked list.

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node* prev;
    
    Node(int x) {
        data = x;
        next = nullptr;
          prev = nullptr;
    }
};

// Function to insert a node at the end of 
// the doubly circular linked list
Node* insertAtEnd(Node* head, int newData) {
    Node* newNode = new Node(newData);
    
    if (!head) {
      
        // List is empty
        newNode->next = newNode->prev = newNode;
        head = newNode;
    } else {
      
        // List is not empty
        Node* last = head->prev; 
        
        // Insert new node at the end
        newNode->next = head;
        newNode->prev = last;
        last->next = newNode;
        head->prev = newNode;
    }
    
    return head;
}

void printList(Node* head) {
    if (!head) return;
    Node* curr = head;
    do {
        cout << curr->data << " ";
        curr = curr->next;
    } while (curr != head);
    cout << endl;
}

int main() {
  
    // Linked List : 10<->20<->30
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->prev = head;
    head->next->next = new Node(30);
    head->next->next->prev = head->next;
    head->next->next->next = head;
    head->prev = head->next->next;

    head = insertAtEnd(head, 5);
    printList(head);

    return 0;
}
C
// C code of insert node at End in 
// doubly Circular linked list.

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

struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
};

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

// Function to insert a node at the end 
// of the doubly circular linked list
struct Node* insertAtEnd(struct Node* head, int newData) {
    struct Node* newNode = createNode(newData);
    
    if (!head) {
      
        // List is empty
        newNode->next = newNode->prev = newNode;
        head = newNode;
    } else {
      
        // List is not empty
        struct Node* last = head->prev; 
        
        // Insert new node at the end
        newNode->next = head;
        newNode->prev = last;
        last->next = newNode;
        head->prev = newNode;
    }
    
    return head;
}

void printList(struct Node* head) {
    if (!head) return;
    struct Node* curr = head;
    do {
        printf("%d ", curr->data);
        curr = curr->next;
    } while (curr != head);
    printf("\n");
}

int main() {
  
    // Linked List : 10<->20<->30
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->prev = head;
    head->next->next = createNode(30);
    head->next->next->prev = head->next;
    head->next->next->next = head;
    head->prev = head->next->next;

    head = insertAtEnd(head, 5);
    printList(head);

    return 0;
}
Java
// Java code of insert node at End in 
// doubly Circular linked list.

class Node {
    int data;
    Node next;
    Node prev;

    Node(int x) {
        data = x;
        next = null;
          prev = null;
    }
}

class GfG {
  
    // Function to insert a node at the end 
    // of the doubly circular linked list
    static Node insertAtEnd(Node head, int newData) {
        Node newNode = new Node(newData);

        if (head == null) {
          
            // List is empty
            newNode.next = newNode.prev = newNode;
            head = newNode;
        } else {
          
            // List is not empty
            Node last = head.prev; 

            // Insert new node at the end
            newNode.next = head;
            newNode.prev = last;
            last.next = newNode;
            head.prev = newNode;
        }

        return head;
    }

    static void printList(Node head) {
        if (head == null) return;
        Node curr = head;
        do {
            System.out.print(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        System.out.println();
    }

    public static void main(String[] args) {
      
        // Linked List : 10<->20<->30
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.prev = head;
        head.next.next = new Node(30);
        head.next.next.prev = head.next;
        head.next.next.next = head;
        head.prev = head.next.next;

        head = insertAtEnd(head, 5);
        printList(head);
    }
}
Python
# Python code of insert node at End in 
# doubly Circular linked list.

class Node:
    def __init__(self, x):
        self.data = x
        self.next = self.prev = None

def insert_at_end(head, new_data):
    new_node = Node(new_data)
    
    if head is None:
      
        # List is empty
        new_node.next = new_node.prev = new_node
        head = new_node
    else:
      
        # List is not empty
        last = head.prev 
        
        # Insert new node at the end
        new_node.next = head
        new_node.prev = last
        last.next = new_node
        head.prev = new_node
    
    return head

def print_list(head):
    if head is None:
        return
    curr = head
    while True:
        print(curr.data, end=" ")
        curr = curr.next
        if curr == head:
            break
    print()

if __name__ == "__main__":
  
    # Linked List : 10<->20<->30
    head = Node(10)
    head.next = Node(20)
    head.next.prev = head
    head.next.next = Node(30)
    head.next.next.prev = head.next
    head.next.next.next = head
    head.prev = head.next.next

    head = insert_at_end(head, 5)
    print_list(head)
C#
// Python code of insert node at End in 
// doubly Circular linked list.
using System;

class Node {
    public int Data;
    public Node next;
    public Node prev;

    public Node(int x) {
        Data = x;
        next = null;
          prev = null;
    }
}

class GfG {
  
    // Function to insert a node at the end of 
    // the doubly circular linked list
    static Node InsertAtEnd(Node head, int newData) {
        Node newNode = new Node(newData);

        if (head == null) {
          
            // List is empty
            newNode.next = newNode.prev = newNode;
            head = newNode;
        } else {
          
            // List is not empty
            Node last = head.prev; 

            // Insert new node at the end
            newNode.next = head;
            newNode.prev = last;
            last.next = newNode;
            head.prev = newNode;
        }

        return head;
    }

    static void PrintList(Node head) {
        if (head == null) return;
        Node curr = head;
        do {
            Console.Write(curr.Data + " ");
            curr = curr.next;
        } while (curr != head);
        Console.WriteLine();
    }

    static void Main() {
      
        // Linked List : 10<->20<->30
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.prev = head;
        head.next.next = new Node(30);
        head.next.next.prev = head.next;
        head.next.next.next = head;
        head.prev = head.next.next;
      
        head = InsertAtEnd(head, 5);
        PrintList(head);
    }
}
JavaScript
// Javascript code of insert node at End in 
// doubly Circular linked list.
class Node {
    constructor(x) {
        this.data = x;
        this.next = this.prev = null;
    }
}

// Function to insert a node at the 
// end of the doubly circular linked list
function insertAtEnd(head, newData) {
    const newNode = new Node(newData);
    
    if (head === null) {
    
        // List is empty
        newNode.next = newNode.prev = newNode;
        head = newNode;
    } else {
    
        // List is not empty
        const last = head.prev;
        
        // Insert new node at the end
        newNode.next = head;
        newNode.prev = last;
        last.next = newNode;
        head.prev = newNode;
    }
    
    return head;
}

function printList(head) {
    if (head === null) return;
    let curr = head;
    do {
        console.log(curr.data + " ");
        curr = curr.next;
    } while (curr !== head);
    console.log();
}

// Linked List : 10<->20<->30
let head = new Node(10);
head.next = new Node(20);
head.next.prev = head;
head.next.next = new Node(30);
head.next.next.prev = head.next;
head.next.next.next = head;
head.prev = head.next.next;

head = insertAtEnd(head, 5);
printList(head);

Output
10 20 30 5 

Time Complexity: O(1). Since we are not travesing the list.
Auxiliary Space: O(1)

Insertion after a given node in Doubly Circular Linked List – O(n) Time and O(1) Space:

To insert a new node after a given node in doubly circular linked list,

  • Allocate memory for the new node.
  • Traverse the list to locate given node.
  • Insert the newNode:
    • Set newNode->next to given node’next.
    • Set newNode->prev to givenNode.
    • Update givenNode->next->prev to newNode.
    • Update givenNode->next to newNode.
    • If givenNode is the last node (i.e., points to head), update head->prev to newNode.
C++
// C++ code of insert after given node in 
// doubly Circular linked list.

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node* prev;
    
    Node(int x) {
        data = x;
        next = nullptr;
          prev = nullptr;
    }
};

// Function to insert a node after a given node in 
// the doubly circular linked list
Node* insertAfterNode(Node* head, int newData, int givenData) {
    Node* newNode = new Node(newData);
    
      // If the list is empty, return nullptr
    if (!head) return nullptr; 

    // Find the node with the given data
    Node* curr = head;
    do {
        if (curr->data == givenData) {
          
            // Insert the new node after the given node
            newNode->next = curr->next;
            newNode->prev = curr;

            curr->next->prev = newNode;
            curr->next = newNode;

            // If the given node was the last node, 
              // update head's prev
            if (curr == head->prev) {
                head->prev = newNode;
            }
          
            // Return the updated head
            return head; 
        }
        curr = curr->next;
    } while (curr != head);

    return head; 
}

void printList(Node* head) {
    if (!head) return;
    Node* curr = head;
    do {
        cout << curr->data << " ";
        curr = curr->next;
    } while (curr != head);
    cout << endl;
}

int main() {
  
    // Linked List : 10<->20<->30
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->prev = head;
    head->next->next = new Node(30);
    head->next->next->prev = head->next;
    head->next->next->next = head;
    head->prev = head->next->next;

    head = insertAfterNode(head, 5, 10);
    printList(head);

    return 0;
}
C
// C code to insert a node after a given node in 
// a doubly circular linked list

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

struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
};


struct Node* createNode(int x);

// Function to insert a node after a given node in 
// the doubly circular linked list
struct Node* insertAfterNode(struct Node* head, int newData, int givenData) {
    struct Node* newNode = createNode(newData);
    
    // If the list is empty, return nullptr
    if (!head) return NULL;

    // Find the node with the given data
    struct Node* curr = head;
    do {
        if (curr->data == givenData) {
          
            // Insert the new node after the given node
            newNode->next = curr->next;
            newNode->prev = curr;

            curr->next->prev = newNode;
            curr->next = newNode;

            // If the given node was the last node, 
              // update head's prev
            if (curr == head->prev) {
                head->prev = newNode;
            }
          
            // Return the updated head
            return head; 
        }
        curr = curr->next;
    } while (curr != head);

    return head; 
}


void printList(struct Node* head) {
    if (!head) return;
    struct Node* curr = head;
    do {
        printf("%d ", curr->data);
        curr = curr->next;
    } while (curr != head);
    printf("\n");
}

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

int main() {
  
    // Linked List : 10<->20<->30
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->prev = head;
    head->next->next = createNode(30);
    head->next->next->prev = head->next;
    head->next->next->next = head;
    head->prev = head->next->next;
  
    head = insertAfterNode(head, 5, 10);
    printList(head);

    return 0;
}
Java
// Java code to insert after a given node in 
// a doubly circular linked list.

class Node {
    int data;
    Node next;
    Node prev;

    Node(int data) {
        this.data = data;
        next = null;
          prev = null;
    }
}


class GfG {
  
    // Function to insert a node after a given node in 
    // the doubly circular linked list
    static Node insertAfterNode(Node head, int newData, int givenData) {
        Node newNode = new Node(newData);
        
        // If the list is empty, return null
        if (head == null) return null;

        // Find the node with the given data
        Node curr = head;
        do {
            if (curr.data == givenData) {
                
                // Insert the new node after the given node
                newNode.next = curr.next;
                newNode.prev = curr;

                curr.next.prev = newNode;
                curr.next = newNode;

                // If the given node was the last node, 
                  // update head's prev
                if (curr == head.prev) {
                    head.prev = newNode;
                }
                
                // Return the updated head
                return head;
            }
            curr = curr.next;
        } while (curr != head);

        return head;
    }
  
    static void printList(Node head) {
        if (head == null) return;
        Node curr = head;
        do {
            System.out.print(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        System.out.println();
    }

    public static void main(String[] args) {
      
        //Linked List : 10<->20<->30
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.prev = head;
        head.next.next = new Node(30);
        head.next.next.prev = head.next;
        head.next.next.next = head;
        head.prev = head.next.next;

        head = insertAfterNode(head, 5, 10);
        printList(head);
    }
}
Python
# Python code to insert a node after a given node 
# in a doubly circular linked list

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None

# Function to insert a node after a given node in 
# the doubly circular linked list
def insertAfterNode(head, newData, givenData):
    newNode = Node(newData)
    
    # If the list is empty, return None
    if not head:
        return None
    
    # Find the node with the given data
    curr = head
    while True:
        if curr.data == givenData:
            
            # Insert the new node after the given node
            newNode.next = curr.next
            newNode.prev = curr

            curr.next.prev = newNode
            curr.next = newNode

            # If the given node was the last node,
            # update head's prev
            if curr == head.prev:
                head.prev = newNode
            
            # Return the updated head
            return head

        curr = curr.next
        if curr == head:
            break

    return head

def printList(head):
    if not head:
        return
    curr = head
    while True:
        print(curr.data, end=" ")
        curr = curr.next
        if curr == head:
            break
    print()

if __name__ == "__main__":
  
    # Linked List : 10<->20<->30
    head = Node(10)
    head.next = Node(20)
    head.next.prev = head
    head.next.next = Node(30)
    head.next.next.prev = head.next
    head.next.next.next = head
    head.prev = head.next.next

    head = insertAfterNode(head, 5, 10)
    printList(head)
C#
// C# code to insert after a given node in a 
// doubly circular linked list.

using System;

class Node {
    public int data;
    public Node next;
    public Node prev;
  
    public Node(int data) {
        this.data = data;
        next = prev = null;
    }
}

class GfG {
  
    // Function to insert a node after a given node in 
    // the doubly circular linked list
    static Node InsertAfterNode(Node head, int newData, int givenData) {
        Node newNode = new Node(newData);
        
        // If the list is empty, return null
        if (head == null) return null;

        // Find the node with the given data
        Node curr = head;
        do {
            if (curr.data == givenData) {
                
                // Insert the new node after the given node
                newNode.next = curr.next;
                newNode.prev = curr;

                curr.next.prev = newNode;
                curr.next = newNode;

                // If the given node was the last node,
                  // update head's prev
                if (curr == head.prev) {
                    head.prev = newNode;
                }
                
                // Return the updated head
                return head;
            }
            curr = curr.next;
        } while (curr != head);

        return head;
    }

       static void PrintList(Node head) {
        if (head == null) return;
        Node curr = head;
        do {
            Console.Write(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        Console.WriteLine();
    }

    static void Main(string[] args) {
      
       //Linked List : 10<->20<->30
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.prev = head;
        head.next.next = new Node(30);
        head.next.next.prev = head.next;
        head.next.next.next = head;
        head.prev = head.next.next;
      
        head = InsertAfterNode(head, 5, 10);
        PrintList(head);
    }
}
JavaScript
// JavaScript code to insert after a given node 
// in a doubly circular linked list.

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}

// Function to insert a node after a given node in 
// the doubly circular linked list
function insertAfterNode(head, newData, givenData) {
    let newNode = new Node(newData);

    // If the list is empty, return null
    if (!head) return null;

    // Find the node with the given data
    let curr = head;
    do {
        if (curr.data === givenData) {
            
            // Insert the new node after the given node
            newNode.next = curr.next;
            newNode.prev = curr;

            curr.next.prev = newNode;
            curr.next = newNode;

            // If the given node was the last node,
            // update head's prev
            if (curr === head.prev) {
                head.prev = newNode;
            }
            
            // Return the updated head
            return head;
        }
        curr = curr.next;
    } while (curr !== head);

    return head;
}

function printList(head) {
    if (!head) return;
    let curr = head;
    do {
        console.log(curr.data + " ");
        curr = curr.next;
    } while (curr !== head);
    console.log();
}

// Linked List : 10<->20<->30
let head = new Node(10);
head.next = new Node(20);
head.next.prev = head;
head.next.next = new Node(30);
head.next.next.prev = head.next;
head.next.next.next = head;
head.prev = head.next.next;

head = insertAfterNode(head, 5, 10);
printList(head);

Output
10 5 20 30 

Time Complexity: O(n), Traversing over the linked list of size n
Auxiliary Space: O(1)

Insertion before a given node in Doubly Circular Linked List – O(n) Time and O(1) Space:

To insert a new node before a specific node in doubly circular linked list,

  • Allocate memory for the new node.
  • Traverse the list to locate the givenNode.
  • Insert the New Node:
    • Set newNode->next to givenNode.
    • Set newNode->prev to givenNode->prev.
    • Update givenNode->prev->next to newNode.
    • Update givenNode->prev to newNode.
  • Update Head (if givenNode is the head node), set head to newNode.
C++
// C++ code to insert before a given node in 
// a doubly circular linked list.

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node* prev;
    
    Node(int x) {
        data = x;
        next = nullptr;
          prev = nullptr;
    }
};

// Function to insert a node before a given node in 
// the doubly circular linked list
Node* insertBeforeNode(Node* head, int newData, int givenData) {
    Node* newNode = new Node(newData);

    // If the list is empty, return nullptr
    if (!head) return nullptr;

    // Find the node with the given data
    Node* curr = head;
    do {
        if (curr->data == givenData) {
          
            // Insert the new node before the given node
            newNode->next = curr;
            newNode->prev = curr->prev;

            curr->prev->next = newNode;
            curr->prev = newNode;

            // If the given node was the head, 
              // update the head
            if (curr == head) {
                head = newNode;
            }

            // Return the updated head
            return head;
        }
        curr = curr->next;
    } while (curr != head);

    return head;
}

void printList(Node* head) {
    if (!head) return;
    Node* curr = head;
    do {
        cout << curr->data << " ";
        curr = curr->next;
    } while (curr != head);
    cout << endl;
}

int main() {
  
    // Linked List : 10<->20<->30
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->prev = head;
    head->next->next = new Node(30);
    head->next->next->prev = head->next;
    head->next->next->next = head;
    head->prev = head->next->next;

    head = insertBeforeNode(head, 5, 30);
    printList(head);

    return 0;
}
C
// C code to insert a node befor a given node in 
// a doubly circular linked list

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

struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
};

struct Node* createNode(int x);

// Function to insert a node before a given node in 
// the doubly circular linked list
struct Node* insertBeforeNode(struct Node* head, int newData, int givenData) {
    struct Node* newNode = createNode(newData);

    // If the list is empty, return nullptr
    if (!head) return NULL;

    // Find the node with the given data
    struct Node* curr = head;
    do {
        if (curr->data == givenData) {
          
            // Insert the new node before the given node
            newNode->next = curr;
            newNode->prev = curr->prev;

            curr->prev->next = newNode;
            curr->prev = newNode;

            // If the given node was the head, update the head
            if (curr == head) {
                head = newNode;
            }

            // Return the updated head
            return head;
        }
        curr = curr->next;
    } while (curr != head);

    return head;
}

void printList(struct Node* head) {
    if (!head) return;
    struct Node* curr = head;
    do {
        printf("%d ", curr->data);
        curr = curr->next;
    } while (curr != head);
    printf("\n");
}

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

int main() {
  
     //Linked List : 10<->20<->30
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->prev = head;
    head->next->next = createNode(30);
    head->next->next->prev = head->next;
    head->next->next->next = head;
    head->prev = head->next->next;

    head = insertBeforeNode(head, 5, 30);
    printList(head);

    return 0;
}
Java
// Java code to insert before a given node in 
// a doubly circular linked list.

class Node {
    int data;
    Node next;
    Node prev;

    Node(int x) {
        data = x;
        next = null;
          prev = null;
    }
}

// Function to insert a node before a given node in 
// the doubly circular linked list
class GfG {
    static Node insertBeforeNode(Node head, int newData, int givenData) {
        Node newNode = new Node(newData);

        // If the list is empty, return null
        if (head == null) return null;

        // Find the node with the given data
        Node curr = head;
        do {
            if (curr.data == givenData) {
              
                // Insert the new node before the given node
                newNode.next = curr;
                newNode.prev = curr.prev;

                curr.prev.next = newNode;
                curr.prev = newNode;

                // If the given node was the head, 
                  // update the head
                if (curr == head) {
                    head = newNode;
                }

                // Return the updated head
                return head;
            }
            curr = curr.next;
        } while (curr != head);

        return head;
    }

    static void printList(Node head) {
        if (head == null) return;
        Node curr = head;
        do {
            System.out.print(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        System.out.println();
    }

    public static void main(String[] args) {
      
        // Linked List : 10<->20<->30
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.prev = head;
        head.next.next = new Node(30);
        head.next.next.prev = head.next;
        head.next.next.next = head;
        head.prev = head.next.next;
      
        head = insertBeforeNode(head, 5, 30);
        printList(head);
    }
}
Python
# Python code to insert before a given node in 
# a doubly circular linked list.

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None

# Function to insert a node before a given node in 
# the doubly circular linked list
def insertBeforeNode(head, newData, givenData):
    newNode = Node(newData)

    # If the list is empty, return None
    if not head:
        return None

    # Find the node with the given data
    curr = head
    while True:
        if curr.data == givenData:
          
            # Insert the new node before the given node
            newNode.next = curr
            newNode.prev = curr.prev

            curr.prev.next = newNode
            curr.prev = newNode

            # If the given node was the head, 
            # update the head
            if curr == head:
                head = newNode

            # Return the updated head
            return head
        curr = curr.next
        if curr == head:
            break

    return head

def printList(head):
    if not head:
        return
    curr = head
    while True:
        print(curr.data, end=" ")
        curr = curr.next
        if curr == head:
            break
    print()

if __name__ == "__main__":
  
    # Linked List : 10<->20<->30
    head = Node(10)
    head.next = Node(20)
    head.next.prev = head
    head.next.next = Node(30)
    head.next.next.prev = head.next
    head.next.next.next = head
    head.prev = head.next.next 
    
    head = insertBeforeNode(head, 5, 30)
    printList(head)
C#
// C# code to insert before a given node in 
// a doubly circular linked list.

using System;

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

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

// Function to insert a node before a given node in 
// the doubly circular linked list
class GfG {
    static Node InsertBeforeNode(Node head, int newData, int givenData) {
        Node newNode = new Node(newData);

        // If the list is empty, return null
        if (head == null) return null;

        // Find the node with the given data
        Node curr = head;
        do {
            if (curr.data == givenData) {
              
                // Insert the new node before the given node
                newNode.next = curr;
                newNode.prev = curr.prev;

                curr.prev.next = newNode;
                curr.prev = newNode;

                // If the given node was the head, 
                  //update the head
                if (curr == head) {
                    head = newNode;
                }

                // Return the updated head
                return head;
            }
            curr = curr.next;
        } while (curr != head);

        return head;
    }

    static void PrintList(Node head) {
        if (head == null) return;
        Node curr = head;
        do {
            Console.Write(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        Console.WriteLine();
    }

    static void Main(string[] args) {
      
        // Linked List : 10<->20<->30
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.prev = head;
        head.next.next = new Node(30);
        head.next.next.prev = head.next;
        head.next.next.next = head;
        head.prev = head.next.next;

        head = InsertBeforeNode(head, 5, 30);
        PrintList(head);
    }
}
JavaScript
// JavaScript code to insert before a given node in 
// a doubly circular linked list.

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}

// Function to insert a node before a given node in 
// the doubly circular linked list
function insertBeforeNode(head, newData, givenData) {
    let newNode = new Node(newData);

    // If the list is empty, return null
    if (!head) return null;

    // Find the node with the given data
    let curr = head;
    do {
        if (curr.data === givenData) {
        
            // Insert the new node before the given node
            newNode.next = curr;
            newNode.prev = curr.prev;

            curr.prev.next = newNode;
            curr.prev = newNode;

            // If the given node was the head, 
            // update the head
            if (curr === head) {
                head = newNode;
            }

            // Return the updated head
            return head;
        }
        curr = curr.next;
    } while (curr !== head);

    return head;
}

function printList(head) {
    if (!head) return;
    let curr = head;
    do {
        console.log(curr.data + " ");
        curr = curr.next;
    } while (curr !== head);
    console.log();
}

// Linked List : 10<->20<->30
let head = new Node(10);
head.next = new Node(20);
head.next.prev = head;
head.next.next = new Node(30);
head.next.next.prev = head.next;
head.next.next.next = head;
head.prev = head.next.next;

head = insertBeforeNode(head, 5, 30);
printList(head);

Output
10 20 5 30 

Time Complexity: O(n), Traversing over the linked list of size n
Auxiliary Space: O(1)

Insertion at a specific position in Doubly Circular Linked List – O(n) Time and O(1) Space:

To insert a new node at a specific position in doubly circular linked list,

  • Allocate memory for the new node.
  • Initialize a pointer curr pointer to the head node and start traversing the list we reach the node just before the desired position. Use a counter to keep track of the curr position.
  • Insert the New Node:
    • Set newNode->next to curr->next.
    • Set newNode->prev to curr.
    • Update curr->next->prev to newNode.
    • Update current->next to newNode.
  • Update Head (if the insertion is at position 0 and the list is empty), set head to newNode.
C++
// C++ code to insert a new node at a specific position in 
// a doubly circular linked list.

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node* prev;
    
    Node(int x) {
        data = x;
        next = nullptr;
          prev = nullptr;
    }
};

// Function to add a node after a given position in 
// the doubly circular linked list
Node* addNode(Node* head, int pos, int newData) {
    Node* newNode = new Node(newData);
    
    // If the list is empty, return nullptr
    if (!head) {
          if (pos > 1) {
             return nullptr; 
        }
          // New node becomes the only node in the circular list
         newNode->prev = newNode;
          newNode->next = newNode;
          return newNode; 
    }
  
    if (pos == 1) {
         // Insert at the beginning of the list
        newNode->next = head;
        newNode->prev = head->prev;
        head->prev->next = newNode;
        head->prev = newNode;
        return newNode;
    }

    // Traverse to the p-th position
    Node* curr = head;
    for (int i = 1; i < pos - 1; i++) {
        curr = curr->next;
        if (curr == head) {
            cout << "Position out of range!" << endl;
            return head;
        }
    }

    // Insert the new node after the 
      // current node (at the given position)
    newNode->next = curr->next;
    newNode->prev = curr;

    if (curr->next != nullptr) {
        curr->next->prev = newNode;
    }
    curr->next = newNode;

    // Return the updated head
    return head;
}

void printList(Node* head) {
    if (!head) return;
    Node* curr = head;
    do {
        cout << curr->data << " ";
        curr = curr->next;
    } while (curr != head);
    cout << endl;
}

int main() {
  
    // Linked List : 10<->20<->30
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->prev = head;
    head->next->next = new Node(30);
    head->next->next->prev = head->next;
    head->next->next->next = head;
    head->prev = head->next->next;
  
    head = addNode(head, 2, 5);
    printList(head);

    return 0;
}
C
// C code to insert a new node at a specific position in 
// a doubly circular linked list.

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

struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
};

struct Node* createNode(int x);

// Function to add a node after a given position in 
// the doubly circular linked list
struct Node* addNode(struct Node* head, int pos, int newData) {
    struct Node* newNode = createNode(newData);
    
    // If the list is empty, return nullptr
    if (!head) {
          if (pos > 1) {
             return NULL; 
        }
          // New node becomes the only node in the circular list
         newNode->prev = newNode;
          newNode->next = newNode;
          
          // New node becomes the head
          return newNode;  
    }
  
    if (pos == 1) {
         // Insert at the beginning of the list
        newNode->next = head;
        newNode->prev = head->prev;
        head->prev->next = newNode;
        head->prev = newNode;
      
          // New node becomes the head
        return newNode; 
    }

    // Traverse to the p-th position
    struct Node* curr = head;
    for (int i = 1; i < pos - 1; i++) {
        curr = curr->next;
        if (curr == head) {
            printf("Position out of range!\n");
            return head;
        }
    }

    // Insert the new node after the 
      // current node (at the given position)
    newNode->next = curr->next;
    newNode->prev = curr;

    if (curr->next != NULL) {
        curr->next->prev = newNode;
    }
    curr->next = newNode;

    // Return the updated head
    return head;
}

void printList(struct Node* head) {
    if (!head) return;
    struct Node* curr = head;
    do {
        printf("%d ", curr->data);
        curr = curr->next;
    } while (curr != head);
    printf("\n");
}

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

int main() {
  
    // Linked List : 10<->20<->30
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->prev = head;
    head->next->next = createNode(30);
    head->next->next->prev = head->next;
    head->next->next->next = head;
    head->prev = head->next->next;
  
    head = addNode(head, 2, 5);
    printList(head);

    return 0;
}
Java
// Java code to insert a new node at a specific position in 
// a doubly circular linked list.

class Node {
    int data;
    Node next;
    Node prev;

    Node(int x) {
        data = x;
        next = null;
        prev = null;
    }
}

class GfG {

    // Function to add a node after a given position in
    // the doubly circular linked list
    public static Node addNode(Node head, int pos, int newData) {
        Node newNode = new Node(newData);

        // If the list is empty, return null
        if (head == null) {
            if (pos > 1) {
                return null;
            }
            // New node becomes the only node
            // in the circular list
            newNode.prev = newNode;
            newNode.next = newNode;
          
              // Return new node as head
            return newNode;  
        }

        if (pos == 1) {
          
            // Insert at the beginning of the list
            newNode.next = head;
            newNode.prev = head.prev;
            head.prev.next = newNode;
            head.prev = newNode;
          
              // New node becomes the head
            return newNode; 
        }

        // Traverse to the p-th position
        Node curr = head;
        for (int i = 1; i < pos - 1; i++) {
            curr = curr.next;
            if (curr == head) {
                System.out.println("Position out of range!");
                return head;
            }
        }

        // Insert the new node after the current 
          // node (at the given position)
        newNode.next = curr.next;
        newNode.prev = curr;

        if (curr.next != null) {
            curr.next.prev = newNode;
        }
        curr.next = newNode;

        // Return the updated head
        return head;
    }

    static void printList(Node head) {
        if (head == null) return;
        Node curr = head;
        do {
            System.out.print(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        System.out.println();
    }

    public static void main(String[] args) {
      
        // Linked List: 10<->20<->30
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.prev = head;
        head.next.next = new Node(30);
        head.next.next.prev = head.next;
        head.next.next.next = head;
        head.prev = head.next.next;

        head = addNode(head, 2, 5);
        printList(head);
    }
}
Python
# Python code to insert a new node at a specific position in 
# a doubly circular linked list.

class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
        self.prev = None

# Function to add a node after a given position in 
# the doubly circular linked list
def addNode(head, pos, newData):
    newNode = Node(newData)
    
    # If the list is empty, return None
    if not head:
        if pos > 1:
            return None
          
        # New node becomes the only node in 
        # the circular list
        newNode.prev = newNode
        newNode.next = newNode
        
        # Return new node as head
        return newNode  
    
    if pos == 1:
      
        # Insert at the beginning of the list
        newNode.next = head
        newNode.prev = head.prev
        head.prev.next = newNode
        head.prev = newNode
        
        # New node becomes the head
        return newNode  

    # Traverse to the p-th position
    curr = head
    for i in range(1, pos - 1):
        curr = curr.next
        if curr == head:
            print("Position out of range!")
            return head

    # Insert the new node after the 
    # current node (at the given position)
    newNode.next = curr.next
    newNode.prev = curr

    if curr.next:
        curr.next.prev = newNode
    curr.next = newNode

    # Return the updated head
    return head

def printList(head):
    if not head:
        return
    curr = head
    while True:
        print(curr.data, end=" ")
        curr = curr.next
        if curr == head:
            break
    print()

if __name__ == "__main__":
    
    # Linked List : 10<->20<->30
    head = Node(10)
    head.next = Node(20)
    head.next.prev = head
    head.next.next = Node(30)
    head.next.next.prev = head.next
    head.next.next.next = head
    head.prev = head.next.next
    
    head = addNode(head, 2, 5)
    printList(head)
C#
// C# code to insert a new node at a specific position in 
// a doubly circular linked list.

using System;

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

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

class GfG {

    // Function to add a node after a given position in
    // the doubly circular linked list
    public static Node addNode(Node head, int pos, int newData) {
        Node newNode = new Node(newData);

        // If the list is empty, return null
        if (head == null) {
            if (pos > 1) {
                return null;
            }
            // New node becomes the only node in 
              // the circular list
            newNode.prev = newNode;
            newNode.next = newNode;
          
              // Return new node as head
            return newNode;  
        }

        if (pos == 1) {
          
            // Insert at the beginning of the list
            newNode.next = head;
            newNode.prev = head.prev;
            head.prev.next = newNode;
            head.prev = newNode;
              
              // New node becomes the head
            return newNode; 
        }

        // Traverse to the p-th position
        Node curr = head;
        for (int i = 1; i < pos - 1; i++) {
            curr = curr.next;
            if (curr == head) {
                Console.WriteLine("Position out of range!");
                return head;
            }
        }

        // Insert the new node after the 
          // current node (at the given position)
        newNode.next = curr.next;
        newNode.prev = curr;

        if (curr.next != null) {
            curr.next.prev = newNode;
        }
        curr.next = newNode;

        // Return the updated head
        return head;
    }

    static void printList(Node head) {
        if (head == null) return;
        Node curr = head;
        do {
            Console.Write(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        Console.WriteLine();
    }

    static void Main(string[] args) {
      
        // Linked List: 10<->20<->30
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.prev = head;
        head.next.next = new Node(30);
        head.next.next.prev = head.next;
        head.next.next.next = head;
        head.prev = head.next.next;

        head = addNode(head, 2, 5);
        printList(head);
    }
}
JavaScript
// Javascript code to insert a new node at a specific position in 
// a doubly circular linked list.

class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
        this.prev = null;
    }
}

// Function to add a node after a given position in 
// the doubly circular linked list
function addNode(head, pos, newData) {
    let newNode = new Node(newData);
    
    // If the list is empty, return null
    if (!head) {
        if (pos > 1) {
            return null; 
        }
        
          // New node becomes the only node in
        // the circular list
        newNode.prev = newNode;
        newNode.next = newNode;
        
        // Return new node as head
        return newNode;  
    }
  
    if (pos === 1) {
    
         // Insert at the beginning of the list
        newNode.next = head;
        newNode.prev = head.prev;
        head.prev.next = newNode;
        head.prev = newNode;
        
        // New node becomes the head
        return newNode;
    }

    // Traverse to the p-th position
    let curr = head;
    for (let i = 1; i < pos - 1; i++) {
        curr = curr.next;
        if (curr === head) {
            console.log("Position out of range!");
            return head;
        }
    }

    // Insert the new node after the 
    // current node (at the given position)
    newNode.next = curr.next;
    newNode.prev = curr;

    if (curr.next !== null) {
        curr.next.prev = newNode;
    }
    curr.next = newNode;

    // Return the updated head
    return head;
}

function printList(head) {
    if (!head) return;
    let curr = head;
    do {
        console.log(curr.data + " ");
        curr = curr.next;
    } while (curr !== head);
}

// Linked List : 10<->20<->30
let head = new Node(10);
head.next = new Node(20);
head.next.prev = head;
head.next.next = new Node(30);
head.next.next.prev = head.next;
head.next.next.next = head;
head.prev = head.next.next;

head = addNode(head, 2, 5);
printList(head);

Output
10 5 20 30 

Time Complexity: O(n), Traversing over the linked list of size n. 
Auxiliary Space: O(1)



Next Article

Similar Reads

Practice Tags :
three90RightbarBannerImg
  翻译: