1

I have a class assignment (read: no use of the STL) where I need to create a sorted linked list of objects, but I'm not quite sure how to go about doing this.

The class that I am using contains both integer and string members, but it is only one of these integer members that will be sorted. I currently have a fully functioning linked list template that will successfully run with integer data.

Now my problem lies in converting this to work with my class. When instantiating this linked list, a <Type> must be defined, in this case that type is Poster, after the class Poster that I am sorting. However, in the declaration of the linked list class, there is a declaration and definition of the class Node which reads

class Node
{
public:
    Type Element;
    Node *Next, *Previous;

    Node() : Next(NULL), Previous(NULL) {} // Default constructor
    Node (Type Data, Node *PNode = NULL) : // Non-default constructor
        Element (Data),
        Next (PNode),
        Previous (PNode) {}
};

I'm unsure how this existing definition will work when the members of Poster are introduced when LinkedList<Poster> listOfPosters is declared. Should I replace the above definition of Node with the contents of class Poster, or will Type Element in the node be marked as a sort of catch-all container for the members of class Poster, so that members of Poster can be accessible via Element.GetMemberValue()?

2
  • Hint: class Node needs to be a template much as LinkedList is. Commented Mar 23, 2011 at 2:15
  • Look into Templated classes, which your teacher likely covered. A linked list should be able to handle any arbitrary data type. Commented Mar 23, 2011 at 2:15

2 Answers 2

1

Im guessing that the declaration of the LinkedList class looks something like

template<class Type>
class LinkedList
{ ... }

When the program that uses the linked list class (the main program) instantiates a LinkedList class like following

LinkedList<Poster> myLinkedList;

The compiler, at compile time, generates code from the template, and replaces all occurrences of "Type" with "Poster". Therefore, you dont need to change the linked-list or node class.

Sign up to request clarification or add additional context in comments.

Comments

1

The Node.Element member will store a (by-value) copy of the Poster. There is no need to manually replace anything in the definition of Node; that's the whole point of C++ templates.

When you declare a LinkedList<Poster> object, the compiler will generate a new class and substitute all instances of the Type placeholder with Poster. This will automatically create an appropriate Node class inside the LinkedList<Poster> class that represents nodes which hold a Poster object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.