Aside from the obvious memory leak when an attempt to insert an already existing name is made, your code seems to work fine. It works fine when either 0
or NULL
is used to initialize the pointers. It makes no difference.
(One wild guess I can make is that in your actual calling code (which you do not show), you somehow managed to pass your LinkedList
around by value. Since your LinkedList
does not satisfy the Rule of Three, the integrity of the list got violated, which lead to undefined consequences you observed.)
BTW, by using an extra level of indirection you can simplify your heavily branched appendNode
function into a significantly more compact and almost branchless one
void LinkedList::appendNode(string name, double x, double y)
{
ListNode** pnodePtr;
for (pnodePtr = &head; *pnodePtr != NULL; pnodePtr = &(*pnodePtr)->next)
if ((*pnodePtr)->cityName == name)
break;
if (*pnodePtr == NULL)
{
*pnodePtr = new ListNode(name, x, y);
cout << "Record inserted successfully.\n" << endl;
}
else
cout << "No need to insert again, as this record exists in the existing data set.\n" << endl;
}
(I also eliminated the leak.) Specifically, this technique allows one to avoid writing a dedicated branch for processing the head node.
Also (referring to the full version of the code), in your functions from "delete by coordinate" group you for some reason check both x
and y
coordinates of the head node, but only one coordinate of the other nodes down the list. Why? This is rather weird and does not seem to make much sense. Meanwhile, functions from "search by coordinate" group do not have this issue - they process all nodes consistently.
Also, your displayList
function suffers from a stray return
at the very beginning, which is why it never prints anything. You need to add a pair of {}
to properly group your statements.