Find sum of even and odd nodes in a linked list in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a linked list. Our task is to find the sum of even and odd nodes in a linked list.

Let's take an example to understand the problem,

Input : linked list : 3 -> 2 -> 5 -> 7 -> 1 -> 9
Output : evenSum = 2 ; oddSum = 25

Explanation

evenSum = 2
oddSum = 3 + 5 + 7 + 1 + 9 = 25

Solution Approach

A simple approach to solve the problem is traversing the linked list and checking for even or odd values and adding them to their respective sum value.

Algorithm

  • Step 1 − Traverse the linked list.

    • Step 1.1 − If the value of the current node is even, add it to evenSum.

    • Step 1.2 − If the value of the current node is odd, add it to oddSum.

  • Step 2 − Return oddSum and evenSum.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
struct Node {
   int data;
   Node* next;
};
void insertNode(Node** root, int item) {
   Node *ptr = *root, *temp = new Node;
   temp->data = item;
   temp->next = NULL;
   if (*root == NULL) 
      *root = temp;
   else {
      while (ptr->next != NULL)
         ptr = ptr->next;
      ptr->next = temp;
   }
}
bool isEven(int a){
   return (a % 2);
}
void findEvenAndOddSum(Node* root) {
   int oddSum = 0, evenSum = 0;
   Node* node = root;
   while (node != NULL) {
      if (isEven(node->data))
         evenSum += node->data;
      else 
         oddSum += node->data;
      node = node->next;
   }
   cout<<"Sum of nodes with even value is "<<evenSum<<endl;
   cout<<"Sum of nodes with odd value is "<<oddSum;
}
int main() {
   Node* root = NULL;
   insertNode(&root, 3);
   insertNode(&root, 2);
   insertNode(&root, 5);
   insertNode(&root, 7);
   insertNode(&root, 1);
   insertNode(&root, 9);
   insertNode(&root, 6);
   findEvenAndOddSum(root);
   return 0;
}

Output

Sum of nodes with even value is 25
Sum of nodes with odd value is 8
raja
Updated on 27-Jan-2022 08:18:57

Advertisements