Posted on by Kalkicode
Code Circular Linked List

Insert node at beginning of circular doubly linked list

The problem involves inserting a new node at the beginning 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 beginning 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 beginning, the list will become: 6 <-> 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6.

Idea to Solve the Problem

Insert node at front of circular doubly linked list

To insert a new node at the beginning 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.
  3. Otherwise, update the pointers of the new node and the existing nodes to insert the new node at the beginning.
  4. Finally, update the head pointer to point to the new node.

Pseudocode

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

function insert(value):
    // Create a new node
    new_node = createNode(value)
    if head is NULL:
        // List is empty
        head = new_node
        tail = new_node
    else:
        head.prev = new_node
        tail.next = new_node
        new_node.next = head
        new_node.prev = tail
        head = 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.
  3. If the list is not empty, update the prev pointer of the current head node and the next pointer of the current tail node to point to the new node.
  4. Update the next pointer of the new node to point to the current head node and the prev pointer to point to the current tail node.
  5. Finally, update the head pointer to point to the new node.

Program List

Resultant Output Explanation

For the provided example with the circular doubly linked list: 8 <-> 7 <-> 6 <-> 5 <-> 4 <-> 3 <-> 2 <-> 1, the program will correctly insert a new node with value 9 at the beginning of the list. This will create a new circular doubly linked list: 9 <-> 8 <-> 7 <-> 6 <-> 5 <-> 4 <-> 3 <-> 2 <-> 1 <-> 9.

Time Complexity

The time complexity of inserting a node at the beginning 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.

New Comment