# Sum of all distinct nodes in a linked list

• Difficulty Level : Easy
• Last Updated : 04 Jun, 2021

Given a linked list and it may consist of duplicate nodes. The task is to find the sum of non-duplicate nodes.
Examples:

Input: 1 -> 2 -> 1 -> 3 -> 4 -> 3 -> NULL
Output:
2 and 4 are the only non-duplicate nodes and 2 + 4 = 6.
Input: 1 -> 3 -> 1 -> 3 -> 1 -> 3 -> NULL
Output:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Approach: We traverse the whole linked list and for each node we check throughout the linked list whether the node has duplicate or not. If there is no duplicate node then we add that node to the variable which stores the sum.
Below is the implementation of the above approach:

## C++

 // C++ implementation of the approach#include using namespace std; // Represents a node of linked liststruct Node {    int data;    Node* next;}; // Function to insert node in a linked listvoid insert(Node** head, int item){    Node* ptr = *head;    Node* temp = new Node;     temp->data = item;    temp->next = NULL;     if (*head == NULL)        *head = temp;    else {        while (ptr->next != NULL)            ptr = ptr->next;        ptr->next = temp;    }} // Function to find the sum of non duplicate nodesint sumOfNonDupNode(Node* head){    Node* ptr1 = head;    Node* ptr2;    int sum = 0, flag = 0;     while (ptr1 != NULL) {        ptr2 = head;        bool flag = false;         // Check if current node has some duplicate        while (ptr2 != NULL) {             // Check for duplicate node            if (ptr1 != ptr2 && ptr1->data == ptr2->data) {                flag = true;                break;            }             // Get to the next node            ptr2 = ptr2->next;        }         // If current node is unique        if (!flag)            sum += ptr1->data;         // Get to the next node        ptr1 = ptr1->next;    }    return sum;} // Driver codeint main(){    Node* head = NULL;     insert(&head, 1);    insert(&head, 2);    insert(&head, 1);    insert(&head, 3);    insert(&head, 4);    insert(&head, 3);     cout << sumOfNonDupNode(head) << endl;     return 0;}

## Javascript


Output:
6

My Personal Notes arrow_drop_up