Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Linked Lists 2

Status
Not open for further replies.

AtomicChip

Programmer
May 15, 2001
622
CA
Ok... This question may seem a little basic, but it's something that's been eating away at me for a little while...

When implementing a linked list, most tutorials on that interweb thing show a list's node structure something like the following:

Code:
struct Node
{
    int data;
    Node * next;
    Node * prev;
}

Here's my question: If you were to implement a templated linked list, would you really want the data portion to be a copy of the data and not a pointer to it (the way some of the older C implementations used the void*)? So, something like this:

Code:
template<typename T>
class List
{
//....
struct Node
{
    T * data;
    Node * next;
    Node * prev;
}
}

That way, when dealing with larger data structs, they would not be copied in memory?

I also realize that there may be scope issues with implementing it this way (i.e. the data value being deleted before the list is done with it).

Any thoughts? Suggestions?

Thanks.

-----------------------------------------------
"The night sky over the planet Krikkit is the least interesting sight in the entire universe."
-Hitch Hiker's Guide To The Galaxy
 
I'd just use the STL classes to begin with, but aside from that, I'd use something like this:
Code:
template<typename T>
class List
{
   //....
   struct Node
   {
       T      data;
       Node*  next;
       Node*  prev;
   }
}
and then if I want data to be a pointer, I can use:
Code:
List<Something*>
or if I want it as an object, I can use:
Code:
List<Something>
 
By default you should have a copy in your linked lists, unless you really need to have a reference. First, references to stack variables will become invalid once the linked list goes out of the function it was filled in. Second, storing pointers to dynamically allocated memory might be useful, but then again - allocating and freeing it in one place and having linked list manage its own allocations and freeing seems a better way to go for me.

------------------
When you do it, do it right.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top