I'm trying to write a class Set with linked list to store integers. After compiling and running on my Mac's terminal, this is the output:
[]
[10]
[10, 20]
Segmentation fault: 11
But I was expecting to see the following output:
[]
[10]
[10, 20]
[10, 20]
[10, 20, 30]
I'm wondering if it is a problem with my operator= function, or is it that I cannot use the operator= function with pointers? If this is so, how should I correct the problem so that the program outputs as I expected? I would really appreciate all your help. Thanks in advance!
#include <iostream>
using namespace std;
class Node {
public:
int value;
Node* next;
Node(int n, Node* ptr = NULL) : value(n), next(ptr) {}
};
class Set {
Node* head;
friend ostream& operator<<(ostream&, const Set&);
public:
Set() : head(NULL) {}
Set(const Set& another){ *this = another; }
~Set();
Set& operator+=(const int&);
Set& operator=(const Set&);
};
int main() {
int num1 = 10;
int num2 = 20;
int num3 = 30;
Set set1;
cout << set1;
Set* set2;
set1 += num1;
cout << set1;
set1 += num2;
cout << set1;
set2 = new Set(set1);
cout << *set2;
*set2 += num3;
cout << *set2;
delete set2;
return 0;
}
Set::~Set() {
Node* current = head;
while (current != NULL) {
Node* temp = current;
current = current->next;
delete temp;
}
}
Set& Set::operator+=(const int& aNum) {
if (head == NULL) {
head = new Node(aNum);
return *this;
}
Node* previous = head;
Node* current = head->next;
while (current != NULL) {
previous = current;
current = current->next;
}
previous->next = new Node(aNum);
return *this;
}
Set& Set::operator=(const Set& another) {
if (this != &another) {
Node* current = head;
while (current != NULL) {
Node* temp = current;
current = current->next;
delete temp;
}
Node* anotherCurrent = another.head;
while (anotherCurrent != NULL) {
*this += anotherCurrent->value;
anotherCurrent = anotherCurrent->next;
}
}
return *this;
}
ostream& operator<<(ostream& os, const Set& s) {
os << "[";
for (Node* p = s.head; p != NULL; p = p->next) {
os << p->value;
if (p->next != NULL)
os << ", ";
}
os << "]" << endl;
return os;
}