GeeksforGeeks App
Open App
Browser
Continue

# Modify a Circular Doubly Linked List such that each node stores the sum of all nodes except itself

Given a circular doubly linked list consisting of N nodes, the task is to modify every node of the given Linked List such that each node contains the sum of all nodes except that node.

Examples:

Input: 4 ↔ 5 ↔ 6 ↔7 ↔ 8
Output: 26 ↔ 25 ↔ 24 ↔ 23 ↔ 22
Explanation:
1st Node: Sum of all nodes except itself = (5 + 6 + 7 + 8) = 26.
2nd Node: Sum of all nodes except itself = (4 + 6 + 7 + 8) = 25.
3rd Node: Sum of all nodes except itself = (4 + 5 + 7 + 8) = 24.
4th Node: Sum of all nodes except itself = (4 + 5 + 6 + 8) = 23.
5th Node: Sum of all Nodes except itself = (4 + 5 + 6 + 7) = 25.

Input: 1 ↔ 2
Output:2 ↔ 1

Naive Approach: The simplest approach to solve the problem is to traverse the given circular doubly linked list and for every node, traverse all the nodes and update that node with the sum of all the nodes except that node. After updating all the nodes, print the updated list

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by storing the sum of data of all the nodes in a variable, say S, and then update the given linked list.
Follow the steps below to solve the problem:

Below is the implementation of the above approach:

## Javascript



Output:

Traversal in forward direction
4 5 6 7 8
Traversal in reverse direction
8 7 6 5 4
After updating the node values:
Traversal in forward direction
26 25 24 23 22
Traversal in reverse direction
22 23 24 25 26

Time Complexity: O(N), where N is the total number of nodes in the circular doubly linked list.
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up