我们可以使用继承实现链表吗?

时间:2014-11-21 07:28:24

标签: c++ linked-list

是否可以使用继承实现链接列表?
例如:

 class List {/* ... */}; // abstract class
 class IntList : public List {/* ... */}; // derived class

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是使List基类仅处理节点,即跟踪列表头部,尾部和添加/删除节点。 List类可以具有基本的Node类,该类可以由例如专业化IntList

这样的东西
class List
{
public:
    virtual ~List() {}

protected:
    // Protected constructor so this class can only be inherited
    List() {}

    struct Node
    {
        Node* next;
        Node* prev;
    };

    void add_head(Node*);
    void add_tail(Node*);

    Node* pop_head();
    Node* pop_tail();

    Node* get_head();
    Node* get_tail();

private:
    Node* head;
    Node* tail;
};

class IntList : public List
{
public:
    IntList();
    ~IntList();

    void add_head(int);  // Creates an `IntNode` and calls `add_head` with that
    void add_tail(int);  // Creates an `IntNode` and calls `add_tail` with that

    int pop_head();  // Calls `pop_head` to get the node, and downcast to `IntNode`
    int pop_tail();  // Calls `pop_tail` to get the node, and downcast to `IntNode`

    int get_head();  // Calls `get_head` to get the node, and downcast to `IntNode`
    int get_tail();  // Calls `get_tail` to get the node, and downcast to `IntNode`

private:
    struct IntNode : List::Node
    {
        int value;
    };
};