Posted on by Kalkicode

# Insert node at end of circular doubly linked list

The problem involves inserting a new node at the end of a circular doubly linked list. A circular doubly linked list is a data structure in which each node has pointers to both its previous and next nodes, and the last node's next pointer points back to the first node, creating a loop.

## Problem Statement

Given a circular doubly linked list, the task is to insert a new node at the end of the list while maintaining the circular structure.

## Example

Consider the circular doubly linked list: 1 <-> 2 <-> 3 <-> 4 <-> 5. After inserting a new node with value 6 at the end, the list will become: 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6.

## Idea to Solve the Problem

To insert a new node at the end of a circular doubly linked list, we need to follow these steps:

1. Create the new node with the given value.
2. If the list is empty, make the new node both the head and the tail. Update the next and previous pointers of the new node to point to itself.
3. If the list is not empty, update the pointers of the new node and the existing nodes to insert the new node at the end.
4. Update the `next` pointer of the current tail node to point to the new node and the `prev` pointer of the new node to point to the current tail node.
5. Update the `prev` pointer of the head node to point to the new node and the `next` pointer of the new node to point to the head node.
6. Finally, update the tail pointer to point to the new node.

## Pseudocode

Here's the pseudocode to insert a node at the end of a circular doubly linked list:

``````function insert(value):
// Create a new node
new_node = createNode(value)
// List is empty
tail = new_node
new_node.next = new_node
new_node.prev = new_node
else:
new_node.prev = tail
tail.next = new_node
tail = new_node``````

## Algorithm Explanation

1. Create a new node with the given value using the `createNode` function.
2. Check if the linked list is empty. If it is, make the new node both the head and the tail. Update the `next` and `prev` pointers of the new node to point to itself.
3. If the list is not empty, update the `next` and `prev` pointers of the new node and the existing nodes to insert the new node at the end.
4. Update the `next` pointer of the current tail node to point to the new node and the `prev` pointer of the new node to point to the current tail node.
5. Update the `prev` pointer of the head node to point to the new node and the `next` pointer of the new node to point to the head node.
6. Finally, update the tail pointer to point to the new node.

## Time Complexity

The time complexity of inserting a node at the end of a circular doubly linked list is O(1), as it involves a constant number of pointer updates.

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

Categories
Relative Post