I want to implement the sorted bag(collection) data structure(with a singly-linked list) in C++ and I have a problem when I want to test the add function. This is the test:
SortedBag sb(relation1); (relation1 is e1<=e2)
sb.add(5);
std::cout << sb.size()<<" ";
sb.add(6);
std::cout << sb.size() << " ";
sb.add(0);
std::cout << sb.size() << " ";
sb.add(5);
std::cout << sb.size() << " ";
sb.add(10);
std::cout << sb.size() << " ";
sb.add(8);
std::cout << sb.size() << " ";
And it will print 1 2 3 3 4 5 instead of 1 2 3 4 5 6.
This is the add function:
void SortedBag::add(TComp e) {
Node* auxiliarElement = new Node;
Node* CheckSLL = new Node;
int flagStop = 1;
if (this->head == nullptr)
{
auxiliarElement->value = e;
auxiliarElement->freq = 1;
auxiliarElement->next = nullptr;
this->head = auxiliarElement;
}
else {
CheckSLL = this->head;
while (CheckSLL->next != nullptr && rel(CheckSLL->value, e))
{
if (CheckSLL->value == e) {
CheckSLL->freq += 1;
flagStop = 0;
break;
}
CheckSLL = CheckSLL->next;
}
if (CheckSLL == this->head && flagStop)
{
auxiliarElement->value = e;
auxiliarElement->freq = 1;
auxiliarElement->next = this->head;
this->head = auxiliarElement;
flagStop = 0;
}
if (CheckSLL->value == e && flagStop)
{
CheckSLL->freq += 1;
flagStop = 0;
}
if (flagStop) {
auxiliarElement->value = e;
auxiliarElement->freq = 1;
auxiliarElement->next = nullptr;
CheckSLL->next = auxiliarElement;
}
}
}
The size() functions works fine, I will post that too:
int SortedBag::size() const {
int Size = 0;
Node* goThrough = new Node;
goThrough = this->head;
while (goThrough != nullptr) {
Size += goThrough->freq;
goThrough = goThrough->next;
}
return Size;
}
And I can't find out why it doesn't add the frequency from the second 5. Can somebody help me, please? (the struct Node has value,freq and a pointer to the next Node)