Alright guys, so I’ve been working on a linked list program and I’ve run into a problem. I’m trying to place a piece of data into an already sorted linked list in a sorted fashion. Right now, I’m comparing the pointer data the user gives (Data * newData) to the head (LinkNode * current = head) and I know that’s where my program is failing. I know I have to compare actual values, not memory addresses, but I’m not sure how I would go about doing it. Anybody have any suggestions at all or ideas?
Thanks.
void addSorted(Data * newData)
{
if(head == NULL)
{
head = new LinkNode(newData);
return;
}
LinkNode * current = head;
LinkNode * previous = NULL;
while(current != NULL)
{
if(newData->compareTo(current->data) == -1)
{
LinkNode * newNode = new LinkNode(newData);
newNode->next = current;
if(previous == NULL)
{
current->next = newNode;
}
else
{
newNode->next = previous->next;
previous->next = newNode;
}
return;
}
previous = current;
current = current->next;
}
previous->next = new LinkNode(newData);
}
Simply
assuming that operator< is overloaded for the Data type
The minimal idiomatic way to provide std::less<> compliant weak total ordering (I.o.w. implement operator<):
If you have an large/complicated structure and all the members participating have comparison defined for their types, you can do this neat trick with TR1, Boost or C++11 Tuples: