Hi Guyz.. Im a beginner in C++ and I am having a bit of trouble with this code which is a HW...
The purpose of this program is to read words from a file, store these words in a singly linked list then sort them and re-type them on the same file..
The problem with my code is that it just crashes and exits when it perform the sorting function
This is a member function of the class Link
I really think there is something wrong with Line 4 :)
void LinkSelSort()//added this function to sort elements of a linked list
{
Node *p=Root;
Node *r= Root->getNext();
Node T;
while (p->getNext()){
while(r)
{
if (strcmp(p->getString(),r->getString())>0)
{
strcpy(T.getString(),p->getString());
strcpy(p->getString(),r->getString());
strcpy(r->getString(),T.getString());
}
r=r->getNext();
}
p=p->getNext();
}
if (strcmp(p->getString(),r->getString())>0){// last cell comparison
strcpy(T.getString(),p->getString());
strcpy(p->getString(),r->getString());
strcpy(r->getString(),T.getString());
}
}//end Of LinkSort
while (p->getNext()){
while(r)
{
//...
}
//Here `r' is NULL
p=p->getNext();
}
//Here `p' is the last cell (it has no `next')
if (strcmp(p->getString(),r->getString())>0){//dereferencing a NULL pointer
_ The inner loop will only execute one time, you need to reset `r'
_ You are making too much swaps for a selection sort (also, call a `swap' function)
_ As you've got a list, consider doing `merge sort'