Thread: Singly Linked List Help

  1. #1

    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.

  2. #2


    post ur code

  3. #3
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    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.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Anyone good with linked list.....I am not....
    By chadsxe in forum C++ Programming
    Replies: 11
    Last Post: 11-10-2005, 02:48 PM
  2. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  3. How can I traverse a huffman tree
    By carrja99 in forum C++ Programming
    Replies: 3
    Last Post: 04-28-2003, 05:46 PM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM