使用链接列表中的模板

Using template in linked list

本文关键字:列表 链接      更新时间:2023-10-16

我遇到了这个问题,我需要实现一个链表,但节点中存储的元素的数据类型可能是字符串或指向另一个类的指针

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);
            /* ... */
        }
};

我试着使用模板,但我做不到,我怎么能使用模板呢?

STL有一个std::list模板类,你真的应该使用它。但如果你想实现自己的类,那么试试这样的方法:

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;
    } 
}; 

您可能会做这样的事情:

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;
};

如果能看到这个问题的其他答案,那将是一件有趣的事情。C++不是我最感兴趣的主题,但这个例子应该编译并运行。您知道,在C++中,struct是一种"默认情况下为public"的类,因此您甚至可以在其中包含函数(不过,我宁愿将私有函数添加到列表中)。