I have a datastructure
struct record {
char cont[bufferSize];
record *next;
};
When I add new records to this structure, I want them to be sorted alphabetically. I made this function, that adds record in the right place (by alphabet) in the linked list:
record *start=NULL, *p, *x;
void recAdd(char*temp) {
p = new record;
temp[strlen(temp)] = '\0';
for (int j=0;j<bufferSize;j++) p->cont[j] = temp[j];
if (start==NULL) start=p;
else {
x=start;
int c=0;
while (recComp(x->cont,p->cont) <= 0 && x->next != NULL) {
x=x->next;
c++;
}
if (c == 0) {
p->next=start;
start=p;
}
else {
x=start;
for (int i=0;i<c;i++) x=x->next;
p->next=x->next;
x->next=p;
}
}
for (int j=0;j<bufferSize;j++) temp[j] = NULL;
};
But somehow it doesn’t sort things right. What is wrong with my function?
Your code is a mess. There are a number of problems both semantic and logical, but fundamentaly the logic that decides where to insert new nodes is the most flawed. Change it to this (note my new code in the else block):
BUT the fact that you had enough difficulty writing this code that you would ask SO for help in fixing it illustrates an important point: the best code is code that you never have to write. You have written both a linked list type structure (bare bones tho it may be) and a sorting algorithm. Both are flawed, and both have working, tested and efficient versions available as part of the standard C++ libraries. You should be using them. Use strings instead of char*s. Use vectors instead of your linked list. Use
sortinstead of your hand rolled sorting algorithm. Taken together, all your code can be replaced by this:Why hand-roll a bunch of stuff and expose yourself to countless defects when you can use tools that already work and do what you want?