Using template in linked list

I came across this problem,, i need to implement a linked list, but the data type of element stored in the node may a string or a pointer to another class,

class Node{
    public:
        string data;
        void *link;
        Node *next;

        Node(){
            link = next = NULL;
        }
        Node(string str){
            data = str;
        }
        Node(void *ptr){
            link = ptr;
        }
};

class List{
    Node *head;
    Node *tail;

    public:
        void insert(string str){
            Node *newNode = new Node(str);
            /* ... */
        }
        void insert(void *ptr){
            Node *newNode = new Node(ptr);
            /* ... */
        }
};

I try to use template but i couldn't, how could i use template for this ?

Answers


The STL has a std::list templated class, you really should use it. But if you want to implement your own class then try something like this:

template<typename T>
class Node
{ 
public: 
    Node *next; 
    T data; 

    Node(const T &value)
        : next(NULL), data(value)
    {
    } 
}; 

template<typename T>
class List
{ 
private:
    Node<T> *head; 
    Node<T> *tail; 

public: 
    List()
        : head(NULL), tail(NULL)
    {
    }

    void insert(const T &value)
    { 
        Node<T> *newNode = new Node<T>(value); 
        if (!head)
            head = newNode;
        if (tail)
            tail->next = newNode;
        tail = newNode;
    } 
}; 

You could potentially do something like this:

template <class T>
class List 
{
public:
    List(): root(NULL) {};
    ~List();
    bool add(const T& item);
    ....

private:
    typedef struct Node {
        T item;
        struct Node *next;
    } Node; 
    Node *root;
};

It would be interesting to see other answers to this. C++ is not my strongest topic, but this example should compile and work. You know that in C++ struct is sort of "public-by-default" class so you can even include functions in it (I would rather add private functions to your list instead though).


Need Your Help

opengl - flash of light (like when shooting)

c++ opengl 3d glut

I'm trying to create flash of light (like when someone is shooting). For e.g. (it's from real video, but i need something similar, much more simpler):

Is it possible to pass an anonymous object as argument of an RMI method?

java rmi anonymous-class

I am trying to invoke a remote method via RMI that takes 1 argument of type MyData, which is an interface known in both server side and client side.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.