-1

This is my header file

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

#include <iostream>
#include <string>
using namespace std;

class Node
{
    friend class LinkedList;

public:
    Node(string& name, int num) :studentName(name), RUID(num)
    {
        this->next = NULL;
    }

private:
    string studentName;
    int RUID;
    Node *next;
};

class LinkedList
{
public:
    LinkedList();
    ~LinkedList();

    LinkedList& operator+(LinkedList &i);
    //LinkedList operator=();

    void makeLists(int n);
    void addNode(LinkedList &i);
    void removeNode();
    void printList();
    void printElement();
    void sortList();

private:
    Node *head;
    Node *tail;
    int size;
};

#endif

...and this is my operator+ function

LinkedList& LinkedList::operator+(LinkedList &i)
{
    LinkedList tohma;
    tohma = *this;
    tohma += i;
    return tohma;
}

I'm getting an error message with the += operator but I'm stumped as to how I should do it differently. I get the feeling that I'm close but perhaps I'm making a logical error?

Any and all help would be appreciated

CodingPoding
  • 33
  • 2
  • 9

2 Answers2

0

Typically, operator+ for a LinkedList is structured as follows:

LinkedList operator+(const LinkedList& _list) {

    // ptr to list to return, initialised with this
    LinkedList* ret_list = this;

    // temporary node ptr for iterating through _list
    Node* temp = _list.head;

    // loop through contents of _list
    while (temp != nullptr) {
        // insert data from _list to ret_list
        ret_list->insert(temp->data);  
        // ^= this will need to be changed for your specific list fields and insert methods
        temp = temp->next;
    }

    return &ret_list;

}

As for the operator+=, that has similar logic:

LinkedList& operator+=(const LinkedList& _list) {

    Node* temp = _list.head;

    while (temp != nullptr) {
        insert(temp->data);
        temp = temp->next;
    }        

    return *this;

}

I may have got something wrong here as it's quite late, but it should be accurate.

sjrowlinson
  • 3,297
  • 1
  • 18
  • 35
0
LinkedList LinkedList::operator+(const LinkedList &i)
{
    LinkedList* tohma = this;
    Node* temp = i.head;

    tohma->tail->next = temp;

    return *tohma;
}

Since I already had the tailing node saved for my first list, I was able to use that to concatenate it with the second list

CodingPoding
  • 33
  • 2
  • 9