Hello, I Have a function sort in my program (below) that takes in linked lists and inserts them sorted. I have the function working 100% by last name but when Itry to do it by first name IF the last names are the same I get seg fault when I'm trying to insert a new head node.
edit!! Also, When I enter if both names are the same, I want it to spit out the way I inserted it but it prints it out backwards
Thank you.
I have the name sorting working, i meant in that code it is printing out backwards, I want it when The first and last names are the same to print it out the way I inserted it.
okay, I ran into probems with first name, so I took it out, but here is my entire program..
input:
input <fname> <lname> <phnum> <email>
print (prints the list)
lookupfirst <fname> (displays all parts of list wit the first name you entered)
lookuplast <lname> same as above
remove <fname> <lname> (removes from that node wont delete head node after the list is sorted, error)
header:
I have looked at it but without rewriting the structure I don't know how to fix it. I am used to working with a grounded linked list (a fixed head and tail node). Here is my class, hope it helps.
One problem I see is with line 30: if (m_head == NULL || lname < m_head->m_lname )
If head IS NULL then dereferencing it will not be good (as you do on same line as testing for NULL).
You want something more like...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
if( head == NULL )// then list is empty
{
head = new Address;
head->next = NULL;
}
else// OK to dereference head
{
if( lname < m_head->m_lname )
{
Address* pA = new Address(...);
pA->next = head;
head = pA;
return;
}
// rest of function to search further into list
}
If head IS NULL then dereferencing it will not be good (as you do on same line as testing for NULL).
No, short circuit evaluation will prevent that from happening. If it's null then the expression a || b is true anyway, so the unnecessary check is skipped. If it were written as
if (lname < m_head->m_lname || m_head == NULL)
then it would cause a crash when a null pointer was passed.