Inserting alphabetically into a Linked List
I'm having trouble figuring out how to do this. I think I'm sort of close.
Code:
void compclass::addstudent(char tname[]) {
student *newstud = new student;
student *head = studentlist;
student *tail = studentlist;
int count = 0;
if (count >= 1) {
head = studentlist->retnext();
}
newstud->setname(tname);
if (studentlist == NULL) {
newstud->setnext(NULL);
studentlist = newstud;
count++;
return;
}
else {
if (strcmp(tail->retname(), newstud->retname()) > 0) {
newstud->setnext(studentlist);
studentlist = newstud;
return;
}
while (strcmp(head->retname(), newstud->retname()) < 0) {
if (strcmp(head->retname(), newstud->retname()) < 0) {
newstud->setnext(head);
tail->setnext(newstud);
return;
}
tail = tail->retnext();
head = head->retnext();
}
tail = newstud->retnext();
newstud = head->retnext();
}
}
It just goes into an infinite loop, because somehow I'm linking them to each other. If I add it to where it's alphabetically lower, it works fine. When I add something alphabetically higher however, it actually looks to add ok. But when I try to print the list of students, that's when it goes into the loop.