-
Singly Linked List Help
I really need some help with this. I can create a linked list, traverse it and everything BUT no matter what I do I cannot do it with functions. For example: I can't have my main function call a function to create the list with input from the keyboard, then return to main, then call another function to output it to the monitor. Thanks for your help.
-
-
Post some of your code, you could be having any number of problems, still I'll venture a guess.
You are probably having trouble with managing the memory. Remember to write a copy constructor (so that when passing by value, all the contents of the list get copied), and a destructor, to free all the memory in the list.
Perhaps you have written the destructor, but not the copy constructor. Thus, when you pass the list by value to a function, the default copy constructor is called, which simply copies the value the head pointer points to. You do whatever you want in the function, but when the function ends, the destructor for the "copy" of the list is called. The destructor then sequentially frees all memory starting with the head pointer. When you try to use the original list back in your main, you are trying to use deallocated memory.
You can either
A. Take the cheesy approach and never use the copy constructor (make it private), and always pass by reference.
B. Write a correct copy constructor.
You should write the copy constructor, but note that it is expensive, and pass the lists by reference, using the copy constructor only when you (GASP) want a new list that is a copy of an older one.