Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 422
  • Last Modified:

Linked-List.

To C++ experts,

    When we want to creat a linked-list, is it better to declare  the "ListNode" class and the "Itarator" class as members of the "List" class ? or better to make them separated classes with friend functions ?

    Similarly, should the "TreeNode" class and the "TreeIterator" class be members of the "Tree" class  ? or better to make them separated classes ?

Thanks.

meow.
0
meow00
Asked:
meow00
  • 2
2 Solutions
 
tinchosCommented:
Hi meow00,

If the Iterator class is going to be used only to iterate the List class, I would create it as Inner classes of the List class, as it's existence is limitated only to that class.

I would definitely create the ListNode class as an Inner class of List, as like the case before it's existence is limitated to the List class (ListNodes will only be part of a List, they won't work with other classes).


Example with both classes as inner classes

public class List
{
    public class ListNode
    {
        // Code
    };
    public class Iterator
    {
        // Code
    };
}



Hope this helps
0
 
DexstarCommented:
meow00:

>     When we want to creat a linked-list, is it better to declare  the "ListNode"
> class and the "Itarator" class as members of the "List" class ? or better to
> make them separated classes with friend functions ?

You should study the Standard Template Library, and see how they do it in there.  If you want to be good at C++, it behooves you to learn the STL.  It is very handy.

Hope That Helps,
Dex*
0
 
meow00Author Commented:
Yes, but some STL books have Iterator class and ListNode class inside the List class. However, others prefer to make them different classes. I am sure both ways work, but I don't know which method is better in different situations ....... thanks .....
0
 
DexstarCommented:
Both classes should be derived internally to the list class.  That way, other classes only need to know about the list, and they automatically get access to the node classes (if needed), and to the iterator classes via the typedefs or definitions of the class.  For example:
    List::iterator itr = l.begin();

Anything knowing about List, automatically knows about List::iterator.  If they were separate, this would not be guarenteed.

Dex*
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now