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 = curre开发者_StackOverflownt;
current = current->next;
}
previous->next = new LinkNode(newData);
}
Simply
if(*newData < (*current->data))
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<):
struct Data
{
int id;
std::string other;
// details omitted
bool operator<(const Data& b) const
{
if (id < rhs.id)
return true;
if (id > ths.id)
return false;
return (other < b.other);
}
};
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:
#include <tuple>
// ...
bool operator<(const Data& b) const
{
return std::tie(id,other)< std::tie(b.id,b.other);
}
In your while loop you are comparing newData (which is a pointer) with "current->data" which is an integer (I suppose) ?
i.e. if(newData < current->data)
you could use memcmp to compare your data
if(newData < current->data)
should be
if(*newData < current->data)
I guess. If there is no operator<, implement it or use the slow memcmp.
Also if this is a practical code (why not use stl?) consider using skip lists - they will be much faster.
PS: operators are a powerful feature, do not hesitate to use them.
精彩评论