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:
- Store the sum of the given linked list in a variable, say S.
- Initialize a pointer, temp at the head of the linked list.
- Iterate a loop until the temp→next does not become equal to the head and perform the following steps:
- Update the value of temp → data as (S – temp→data).
- Update temp to temp→next.
- After completing the above steps, update the value of the last node to (S – temp→data) and print the updated linked list.
Below is the implementation of the above approach:
C
// C program for the above approachÂ
#include<stdio.h>#include<stdlib.h>// Structure of a Nodestruct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;Â Â Â Â struct Node* prev;};Â
// Function to insert a node at the// end of the given Linked Listvoid insertEnd(struct Node** start,            int value){    // If the list is empty, then    // create a single node    // circular and doubly list    if (*start == NULL) {Â
        // Create a new Node        struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));Â
        // Add values and links to        // the next & the previous        new_node->data = value;        new_node->next = new_node;        new_node->prev = new_node;Â
        // Update the start        *start = new_node;        return;    }Â
    // If list is not empty, then    // find last node    struct Node* last = (*start)->prev;Â
    // Create Node dynamically    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));    new_node->data = value;Â
    // Start is the next of new_node    new_node->next = *start;Â
    // Make new node previous of start    (*start)->prev = new_node;Â
    // Make last previous of new node    new_node->prev = last;Â
    // Make new node next of old last    last->next = new_node;}Â
// Function to print the linked listvoid display(struct Node* start){    // Forward traversal    struct Node* temp = start;Â
    printf( "Traversal in forward "        "direction \n");    while (temp->next != start) {        printf("%d ",temp->data);        temp = temp->next;    }printf("%d ",temp->data);    // Backward traversal    printf("\nTraversal in reverse"        " direction \n");    struct Node* last = start->prev;    temp = last;Â
    // Traverse the Linked List    while (temp->prev != last) {Â
        // Print the data        printf("%d ",temp->data);        temp = temp->prev;    }Â
    // Print the data    printf("%d ",temp->data);}Â
// Function to find the sum of all// nodes in the given Linked Listint findSum(struct Node* start){    // Stores the sum of all the nodes    int sum = 0;Â
    struct Node* temp = start;Â
    // Traverse the linked list and    // update the sum    while (temp->next != start) {Â
        // Update the sum        sum += temp->data;Â
        // Update the temp        temp = temp->next;    }Â
    // Update the sum    sum += temp->data;Â
    // Return the sum    return sum;}Â
// Function to update the data of// every node with the sum of data// of all nodes except itselfvoid updateNodeValue(struct Node* start){    // Stores the total sum    // of all the nodes    int sum = findSum(start);Â
    struct Node* temp = start;Â
    // Traverse the linked list    // and update each node's data    while (temp->next != start) {Â
        // Update the temp->data        temp->data = sum - temp->data;Â
        // Update the temp        temp = temp->next;    }Â
    // Update the temp->data    temp->data = sum - temp->data;}Â
// Function to construct a// circular doubly linked liststruct Node* formLinkedList(struct Node* start){Â Â Â Â // Given linked list as:Â Â Â Â // 4 <-> 5 <-> 6 <-> 7 <-> 8Â Â Â Â insertEnd(&start, 4);Â Â Â Â insertEnd(&start, 5);Â Â Â Â insertEnd(&start, 6);Â Â Â Â insertEnd(&start, 7);Â Â Â Â insertEnd(&start, 8);Â
    // Return the head of the    // constructed Linked List    return start;}Â
// Driver Codeint main(){    // Linked list formation    struct Node* start = NULL;    start = formLinkedList(start);Â
    // Display the linked list    display(start);Â
    // Function Call    updateNodeValue(start);Â
    // Display the linked list    // after updating nodes    printf("\nAfter updating the node values:\n");Â
    // Print the Linked List    display(start);Â
    return 0;} |
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Structure of a Nodestruct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;Â Â Â Â struct Node* prev;};Â
// Function to insert a node at the// end of the given Linked Listvoid insertEnd(struct Node** start,               int value){    // If the list is empty, then    // create a single node    // circular and doubly list    if (*start == NULL) {Â
        // Create a new Node        struct Node* new_node = new Node();Â
        // Add values and links to        // the next & the previous        new_node->data = value;        new_node->next = new_node;        new_node->prev = new_node;Â
        // Update the start        *start = new_node;        return;    }Â
    // If list is not empty, then    // find last node    Node* last = (*start)->prev;Â
    // Create Node dynamically    struct Node* new_node = new Node;    new_node->data = value;Â
    // Start is the next of new_node    new_node->next = *start;Â
    // Make new node previous of start    (*start)->prev = new_node;Â
    // Make last previous of new node    new_node->prev = last;Â
    // Make new node next of old last    last->next = new_node;}Â
// Function to print the linked listvoid display(struct Node* start){    // Forward traversal    struct Node* temp = start;Â
    cout << "Traversal in forward "           "direction \n";    while (temp->next != start) {        cout << temp->data << " ";        temp = temp->next;    }   cout << temp->data << " " ;Â
    // Backward traversal    cout << "\nTraversal in reverse"           " direction \n";    Node* last = start->prev;    temp = last;Â
    // Traverse the Linked List    while (temp->prev != last) {Â
        // Print the data        cout << temp->data << " " ;        temp = temp->prev;    }Â
    // Print the data    cout << temp->data << " ";}Â
// Function to find the sum of all// nodes in the given Linked Listint findSum(Node*& start){    // Stores the sum of all the nodes    int sum = 0;Â
    Node* temp = start;Â
    // Traverse the linked list and    // update the sum    while (temp->next != start) {Â
        // Update the sum        sum += temp->data;Â
        // Update the temp        temp = temp->next;    }Â
    // Update the sum    sum += temp->data;Â
    // Return the sum    return sum;}Â
// Function to update the data of// every node with the sum of data// of all nodes except itselfvoid updateNodeValue(Node*& start){    // Stores the total sum    // of all the nodes    int sum = findSum(start);Â
    Node* temp = start;Â
    // Traverse the linked list    // and update each node's data    while (temp->next != start) {Â
        // Update the temp->data        temp->data = sum - temp->data;Â
        // Update the temp        temp = temp->next;    }Â
    // Update the temp->data    temp->data = sum - temp->data;}Â
// Function to construct a// circular doubly linked listNode* formLinkedList(Node* start){Â Â Â Â // Given linked list as:Â Â Â Â // 4 <-> 5 <-> 6 <-> 7 <-> 8Â Â Â Â insertEnd(&start, 4);Â Â Â Â insertEnd(&start, 5);Â Â Â Â insertEnd(&start, 6);Â Â Â Â insertEnd(&start, 7);Â Â Â Â insertEnd(&start, 8);Â
    // Return the head of the    // constructed Linked List    return start;}Â
// Driver Codeint main(){    // Linked list formation    struct Node* start = NULL;    start = formLinkedList(start);Â
    // Display the linked list    display(start);Â
    // Function Call    updateNodeValue(start);Â
    // Display the linked list    // after updating nodes    cout << "\nAfter updating "         << "the node values:\n";Â
    // Print the Linked List    display(start);Â
    return 0;} |
Java
// Java program for the above approachclass GFG{Â
static Node start;static class Node {Â Â Â Â int data;Â Â Â Â Node next;Â Â Â Â Node prev;}Â
// Function to insert a node at the// end of the given Linked List// Function to insert at the endstatic void insertEnd(int value){Â
    // If the list is empty, create a single    // node circular and doubly list    if (start == null)     {        Node new_node = new Node();        new_node.data = value;        new_node.next = new_node.prev = new_node;        start = new_node;        return;    }Â
    // If list is not emptyÂ
    // Find last node    Node last = (start).prev;Â
    // Create Node dynamically    Node new_node = new Node();    new_node.data = value;Â
    // Start is going to be    // next of new_node    new_node.next = start;Â
    // Make new node previous of start    (start).prev = new_node;Â
    // Make last previous of new node    new_node.prev = last;Â
    // Make new node next of old last    last.next = new_node;}Â
// Function to print the linked liststatic void display(){Â Â Â Â Node temp = start;Â
    System.out.printf("\nTraversal in " +                       "forward direction \n");    while (temp.next != start)     {        System.out.printf("%d ", temp.data);        temp = temp.next;    }    System.out.printf("%d ", temp.data);Â
    System.out.printf("\nTraversal in reverse " +                     "direction \n");    Node last = start.prev;    temp = last;         while (temp.prev != last)     {        System.out.printf("%d ", temp.data);        temp = temp.prev;    }    System.out.printf("%d ", temp.data);}Â
// Function to update the data of// every node with the sum of data// of all nodes except itselfstatic void updateNodeValue(){         // Stores the total sum    // of all the nodes    int sum = findSum(start);Â
    Node temp = start;Â
    // Traverse the linked list    // and update each node's data    while (temp.next != start)    {                 // Update the temp->data        temp.data = sum - temp.data;Â
        // Update the temp        temp = temp.next;    }Â
    // Update the temp->data    temp.data = sum - temp.data;}Â
static Node formLinkedList(Node start){Â Â Â Â Â Â Â Â Â // Given linked list as:Â Â Â Â // 4 <-> 5 <-> 6 <-> 7 <-> 8Â Â Â Â insertEnd(4);Â Â Â Â insertEnd(5);Â Â Â Â insertEnd(6);Â Â Â Â insertEnd(7);Â Â Â Â insertEnd(8);Â
    // Return the head of the    // constructed Linked List    return start;}Â
// Function to find the sum of all// nodes in the given Linked Liststatic int findSum(Node head){    Node temp = head;         // Stores the sum of all the nodes    int sum = 0;         if (head != null)    {                 // Traverse the linked list and        // update the sum        do        {            temp = temp.next;            sum += temp.data;        } while (temp != head);    }         // Return the sum    return sum;}Â
// Driver codepublic static void main(String args[]){Â Â Â Â Node start = null;Â Â Â Â start = formLinkedList(start);Â
    // Display the linked list    display();Â
    // Function call    updateNodeValue();Â
    // Display the linked list    // after updating nodes    System.out.print("\nAfter updating " +                     "the node value:\n");Â
    // Print the Linked List    display();}}Â
// This code is contributed by abhinavjain194 |
Python3
# Python3 program for the above approachÂ
# Structure of a Nodeclass Node:         def __init__(self, d):                 self.data = d        self.next = None        self.prev = NoneÂ
# Function to insert a node at the# end of the given Linked Listdef insertEnd(start, value):         # If the list is empty, then    # create a single node    # circular and doubly list    if (start == None):Â
        # Create a new Node        new_node = Node(value)Â
        new_node.next = new_node        new_node.prev = new_nodeÂ
        # Update the start        start = new_node        return startÂ
    # If list is not empty, then    # find last node    last = start.prevÂ
    # Create Node dynamically    new_node = Node(value)    new_node.data = valueÂ
    # Start is the next of new_node    new_node.next = startÂ
    # Make new node previous of start    start.prev = new_nodeÂ
    # Make last previous of new node    new_node.prev = lastÂ
    # Make new node next of old last    last.next = new_nodeÂ
    return startÂ
# Function to print the linked listdef display(start):         # Forward traversal    temp = startÂ
    print("Traversal in forward direction")    while (temp and temp.next != start):        print(temp.data, end = " ")        temp = temp.next             print(temp.data, end = " ")Â
    # Backward traversal    print("\nTraversal in reverse direction")    last = start.prev    temp = lastÂ
    # Traverse the Linked List    while (temp.prev != last):Â
        # Print the data        print(temp.data, end = " ")        temp = temp.prevÂ
    # Print the data    print(temp.data, end = " ")Â
# Function to find the sum of all# nodes in the given Linked Listdef findSum(start):         # Stores the sum of all the nodes    sum = 0Â
    temp = startÂ
    # Traverse the linked list and    # update the sum    while (temp.next != start):Â
        # Update the sum        sum += temp.dataÂ
        # Update the temp        temp = temp.nextÂ
    # Update the sum    sum += temp.dataÂ
    # Return the sum    return sumÂ
# Function to update the data of# every node with the sum of data# of all nodes except itselfdef updateNodeValue(start):         # Stores the total sum    # of all the nodes    sum = findSum(start)Â
    temp = startÂ
    # Traverse the linked list    # and update each node's data    while (temp.next != start):Â
        # Update the temp.data        temp.data = sum - temp.dataÂ
        # Update the temp        temp = temp.nextÂ
    # Update the temp.data    temp.data = sum - temp.dataÂ
# Function to construct a# circular doubly linked listdef formLinkedList(start):Â Â Â Â Â Â Â Â Â # Given linked list as:Â Â Â Â # 4 <. 5 <. 6 <. 7 <. 8Â Â Â Â start = insertEnd(start, 4)Â Â Â Â start = insertEnd(start, 5)Â Â Â Â start = insertEnd(start, 6)Â Â Â Â start = insertEnd(start, 7)Â Â Â Â start = insertEnd(start, 8)Â
    # Return the head of the    # constructed Linked List    return startÂ
# Driver Codeif __name__ == '__main__':         # Linked list formation    start = None    start = formLinkedList(start)Â
    # Display the linked list    display(start)Â
    # Function Call    updateNodeValue(start)Â
    # Display the linked list    # after updating nodes    print("\nAfter updating the node values:")Â
    # Print the Linked List    display(start)Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;Â
class GFG{Â
static Node start;public class Node {Â Â Â Â public int data;Â Â Â Â public Node next;Â Â Â Â public Node prev;}Â
// Function to insert a node at the// end of the given Linked List// Function to insert at the endstatic void insertEnd(int value){    Node new_node;         // If the list is empty, create a single    // node circular and doubly list    if (start == null)     {        new_node = new Node();        new_node.data = value;        new_node.next = new_node.prev = new_node;        start = new_node;        return;    }Â
    // If list is not emptyÂ
    // Find last node    Node last = (start).prev;Â
    // Create Node dynamically    new_node = new Node();    new_node.data = value;Â
    // Start is going to be    // next of new_node    new_node.next = start;Â
    // Make new node previous of start    (start).prev = new_node;Â
    // Make last previous of new node    new_node.prev = last;Â
    // Make new node next of old last    last.next = new_node;}Â
// Function to print the linked liststatic void display(){Â Â Â Â Node temp = start;Â
    Console.Write("\nTraversal in " +                   "forward direction \n");                       while (temp.next != start)     {        Console.Write("{0} ", temp.data);        temp = temp.next;    }    Console.Write("{0} ", temp.data);Â
    Console.Write("\nTraversal in reverse " +                     "direction \n");    Node last = start.prev;    temp = last;         while (temp.prev != last)     {        Console.Write("{0} ", temp.data);        temp = temp.prev;    }    Console.Write("{0} ", temp.data);}Â
// Function to update the data of// every node with the sum of data// of all nodes except itselfstatic void updateNodeValue(){         // Stores the total sum    // of all the nodes    int sum = findSum(start);Â
    Node temp = start;Â
    // Traverse the linked list    // and update each node's data    while (temp.next != start)    {                 // Update the temp->data        temp.data = sum - temp.data;Â
        // Update the temp        temp = temp.next;    }Â
    // Update the temp->data    temp.data = sum - temp.data;}Â
static Node formList(Node start){Â Â Â Â Â Â Â Â Â // Given linked list as:Â Â Â Â // 4 <-> 5 <-> 6 <-> 7 <-> 8Â Â Â Â insertEnd(4);Â Â Â Â insertEnd(5);Â Â Â Â insertEnd(6);Â Â Â Â insertEnd(7);Â Â Â Â insertEnd(8);Â
    // Return the head of the    // constructed Linked List    return start;}Â
// Function to find the sum of all// nodes in the given Linked Liststatic int findSum(Node head){    Node temp = head;         // Stores the sum of all the nodes    int sum = 0;         if (head != null)    {                 // Traverse the linked list and        // update the sum        do        {            temp = temp.next;            sum += temp.data;        } while (temp != head);    }         // Return the sum    return sum;}Â
// Driver codepublic static void Main(String []args){Â Â Â Â Node start = null;Â Â Â Â start = formList(start);Â
    // Display the linked list    display();Â
    // Function call    updateNodeValue();Â
    // Display the linked list    // after updating nodes    Console.Write("\nAfter updating " +                  "the node value:\n");Â
    // Print the Linked List    display();}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>// Javascript program for the above approachÂ
// Structure of a Nodeclass Node {Â
    constructor()    {        this.data = 0;        this.next = null;        this.prev = null;    }};Â
// Function to insert a node at the// end of the given Linked Listfunction insertEnd(start, value){    // If the list is empty, then    // create a single node    // circular and doubly list    if (start == null) {Â
        // Create a new Node        var new_node = new Node();Â
        // Add values and links to        // the next & the previous        new_node.data = value;        new_node.next = new_node;        new_node.prev = new_node;Â
        // Update the start        start = new_node;        return start;    }Â
    // If list is not empty, then    // find last node    var last = start.prev;Â
    // Create Node dynamically    var new_node = new Node;    new_node.data = value;Â
    // Start is the next of new_node    new_node.next = start;Â
    // Make new node previous of start    start.prev = new_node;Â
    // Make last previous of new node    new_node.prev = last;Â
    // Make new node next of old last    last.next = new_node;Â
    return start;}Â
// Function to print the linked listfunction display(start){    // Forward traversal    var temp = start;Â
    document.write("Traversal in forward "+           "direction <br>");    while (temp.next != start) {        document.write(temp.data + " ");        temp = temp.next;    }    document.write(temp.data + " ");Â
    // Backward traversal    document.write("<br>Traversal in reverse"+           " direction <br>");    var last = start.prev;    temp = last;Â
    // Traverse the Linked List    while (temp.prev != last) {Â
        // Print the data        document.write( temp.data + " ");        temp = temp.prev;    }Â
    // Print the data    document.write( temp.data + " ");}Â
// Function to find the sum of all// nodes in the given Linked Listfunction findSum(start){    // Stores the sum of all the nodes    var sum = 0;Â
    var temp = start;Â
    // Traverse the linked list and    // update the sum    while (temp.next != start) {Â
        // Update the sum        sum += temp.data;Â
        // Update the temp        temp = temp.next;    }Â
    // Update the sum    sum += temp.data;Â
    // Return the sum    return sum;}Â
// Function to update the data of// every node with the sum of data// of all nodes except itselffunction updateNodeValue(start){    // Stores the total sum    // of all the nodes    var sum = findSum(start);Â
    var temp = start;Â
    // Traverse the linked list    // and update each node's data    while (temp.next != start) {Â
        // Update the temp.data        temp.data = sum - temp.data;Â
        // Update the temp        temp = temp.next;    }Â
    // Update the temp.data    temp.data = sum - temp.data;}Â
// Function to construct a// circular doubly linked listfunction formLinkedList(start){Â Â Â Â // Given linked list as:Â Â Â Â // 4 <. 5 <. 6 <. 7 <. 8Â Â Â Â start = insertEnd(start, 4);Â Â Â Â start = insertEnd(start, 5);Â Â Â Â start = insertEnd(start, 6);Â Â Â Â start = insertEnd(start, 7);Â Â Â Â start = insertEnd(start, 8);Â
    // Return the head of the    // constructed Linked List    return start;}Â
// Driver Code// Linked list formationvar start = null;start = formLinkedList(start);Â
// Display the linked listdisplay(start);Â
// Function CallupdateNodeValue(start);Â
// Display the linked list// after updating nodesdocument.write( "<br>After updating "Â Â Â Â Â + "the node values:<br>");Â Â Â Â Â Â // Print the Linked Listdisplay(start);Â
// This code is contributed by rrrtnx.</script> |
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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



