Для начала эти утверждения
Node* CheckSLL = new Node;
и
Node* goThrough = new Node;
приводят к утечкам памяти.
Также этот вывод
And it will print 1 2 3 3 4 5.
делает не соответствуют последовательности введенных данных, потому что функция size
считает общее значение частот
Size += goThrough->freq;
Так как 6
элементы были вставлены в список, тогда результат должен быть
1 2 3 4 5 6
Отношение должно быть указано как e1 < e2
, а не e1 <= e2
Функцию add
можно определить очень просто. Я предполагаю, что отношение соответствует оператору <. </p>
void SortedBag::add( TComp e )
{
Node **current = &this->head;
while ( *current != nullptr && rel( ( *current )->value, e ) )
{
current = &( *current )->next;
}
if ( *current == nullptr || rel( e, ( *current )->value ) )
{
Node *new_node = new Node;
new_node->value = e;
new_node->freq = 1;
new_node->next = *current;
*current = new_node;
}
else
{
++( *current )->freq;
}
}
. И вы должны решить, возвращает ли функция size
частоты или число узлов в списке.
Вот демонстрационная программа.
#include <iostream>
#include <functional>
template <typename T, typename Comparison = std::less<T>>
class List
{
private:
struct Node
{
T value;
size_t freq;
Node *next;
} *head = nullptr;
Comparison cmp;
public:
explicit List() : cmp( Comparison() )
{
}
explicit List( Comparison cmp ) : cmp( cmp )
{
}
~List()
{
while ( this->head != nullptr )
{
Node *current = this->head;
this->head = this->head->next;
delete current;
}
}
List( const List & ) = delete;
List & operator =( const List & ) = delete;
void add( const T &value );
friend std::ostream & operator <<( std::ostream &os, const List &list )
{
for ( Node *current = list.head; current != nullptr; current = current->next )
{
os << current->value << ':' << current->freq << " -> ";
}
return os << "null";
}
};
template <typename T, typename Comparison>
void List<T, Comparison>::add( const T &value )
{
Node **current = &this->head;
while ( *current != nullptr && cmp( ( *current )->value, value ) )
{
current = &( *current )->next;
}
if ( *current == nullptr || cmp( value, ( *current )->value ) )
{
Node *new_node = new Node { value, 1, *current };
*current = new_node;
}
else
{
++( *current )->freq;
}
}
int main()
{
List<int> list;
list.add( 5 );
list.add( 6 );
list.add( 0 );
list.add( 5 );
list.add( 10 );
list.add( 8 );
std::cout << list << '\n';
return 0;
}
Вывод программы
0:1 -> 5:2 -> 6:1 -> 8:1 -> 10:1 -> null