I’m trying to sort names into alphabetical order inside a linked list but am getting a run time error. what have I done wrong here?
#include <iostream>
#include <string>
using namespace std;
struct node{
string name;
node *next;
};
node *A;
void addnode(node *&listpointer,string newname){
node *temp;
temp = new node;
if (listpointer == NULL){
temp->name = newname;
temp->next = listpointer;
listpointer = temp;
}else{
node *add;
add = new node;
while (true){
if(listpointer->name > newname){
add->name = newname;
add->next = listpointer->next;
break;
}
listpointer = listpointer->next;
}
}
}
int main(){
A = NULL;
string name1 = "bob";
string name2 = "tod";
string name3 = "thomas";
string name4 = "kate";
string name5 = "alex";
string name6 = "jimmy";
addnode(A,name1);
addnode(A,name2);
addnode(A,name3);
addnode(A,name4);
addnode(A,name5);
addnode(A,name6);
while(true){
if(A == NULL){break;}
cout<< "name is: " << A->name << endl;
A = A->next;
}
return 0;
}
I believe the mistake is that you think:
guarantees that listpointer won’t ever be NULL later. However this isn’t the case, for example:
Will print out “oops” then segfault as lispointer is NULL and using -> on a NULL will cause a segfault. This is because in the while (true) loop listpointer eventually reaches the end and gets set to NULL. You then get the segfault.
I think a better idea would be to do something like:
Also this code leaks memory as you don’t delete the things you created with new. You may want to run this (and other code) with valgrind to see what I mean.