Home > Enterprise >  C overloading ' ' operator to get sum of data from 2 different linked lists
C overloading ' ' operator to get sum of data from 2 different linked lists

Time:04-13

I am asked to overload operator ' ' into the list class. I want the sum of all cgpa points of students from 2 different linked lists but don't know how to do it.

#include <iostream>
#include <cstring>
#include<algorithm>

using namespace std;



class StudentGroup
{
public:
 struct Node
 {
  char* name;
  double cgpa;
  Node* next;
 };
 Node* head = 0;
 
public:
 StudentGroup()
 {
  head = nullptr;
 }
 StudentGroup(const StudentGroup &list);
 ~StudentGroup();
 bool insert(char* name, double cgpa);
 bool removeNode(char* name);
 void print();
 double& cumulativeGPA(char* name);
};

above code is what I've done for class definition.

bool StudentGroup::insert(char* name, double cgpa)
{
 bool Insert = false;
 Node* temp;
 Node* newnode = new Node();
 newnode->name = new char[strlen(name) 1];
 strcpy(newnode->name,name);
 newnode->cgpa = cgpa;
 newnode->next = 0;
 if (head == 0)
 {
  head = temp = newnode;
 }
 else
 {
  temp->next = newnode;
  temp = newnode;
 }
 Insert = true;
 return Insert;
}

and here is the code I wrote to create lists and add objects to them.

    int main()
{
 StudentGroup list1, list3, list4;

    list3.insert("Michael Faraday", 4.2);
    list3.insert("Marie Curie", 3.8);
    list4.insert("Albert Einstein", 4.2);
    list4.insert("Alan Turing", 3.8);
 
 //Copy constructor
    StudentGroup list2=list1;
 list1.~StudentGroup();
 list2.print();
 list1.print();

    //Operator overloading
 list3.print();
 list4.print();
 list3 = list4;
}

and above is the main function. What I need is something like:

  list3 list4//code
  16//output     

How to do that? Sorry if my question doesn't fit the usual format, complete beginner here and due to limited time I had to ask.

CodePudding user response:

It's as simple as looping through both lists/groups and adding up their cpga:

// put inside class declaration
double operator (const StudentGroup& student2);

// function definition
double StudentGroup::operator (const StudentGroup& student2)
{
    double ret = 0.0;
    Node* pStudent;

    for (pStudent = this->head; pStudent; pStudent = pStudent->next)
        ret  = pStudent->cgpa;

    for (pStudent = student2.head; pStudent; pStudent = pStudent->next)
        ret  = pStudent->cgpa;

    return ret;
}
  •  Tags:  
  • c
  • Related