C++:关于链表的实现

标签 c++ templates linked-list

我的其中一个函数总是出现编译器错误。

LinkedList.hpp:81: error: `template<class T> class LinkedList' used without template parameters
LinkedList.hpp:81: error: expected constructor, destructor, or type conversion before '*' token
LinkedList.hpp:81: error: expected `;' before '*' token

但问题是我有构造函数、析构函数和类型转换。我很确定实现是错误的

// This is the function i keep on getting an error for
template <class T>
ListNode* LinkedList<T>::find(int pos)//Finds the position of an item
{
    if(pos < 1)
        return NULL; //If pos is less than one then find returns NULL because pos is a illegal value.
    else
    {
        ListNode *temp = head;
        for(int i = 1; i < pos; i++)
            temp = temp -> next;
        return temp;
    } 
}

//The class 
template <class T>
class LinkedList : public ABCList<T> {
private:
    //T    a [LIST_MAX];

    struct ListNode
    {
        T data; // List item
        ListNode *next; //Pointer to next node
    };

    int  size;
    ListNode *head;
    ListNode *find(int pos);

public:
    LinkedList();
    LinkedList(LinkedList &other);
    ~LinkedList();
    virtual bool isEmpty () = 0;
    virtual int  getLength () = 0;
    virtual void insert (int pos, T item) = 0;
    virtual T    remove (int pos) = 0;
    virtual T    retrieve (int pos) = 0;
};

最佳答案

  1. 既然标准库提供了链表,为什么还要创建一个链表? std::list是一个双向链表。
  2. 你能重写ListNode*吗?至 typename LinkedList<T>::ListNode*find()定义
  3. 您必须选择是否希望用户能够操纵 ListNode ,(在这种情况下,您应该将其声明为公共(public)的),或者如果它是实现的一部分(在这种情况下,您可能希望创建某种迭代器)。

I still got the same error

find()的定义位于 LinkedList 声明的顶部类,如问题中所述?如果是这种情况,您应该交换它们。

关于C++:关于链表的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12774302/

相关文章:

c - 推送到仅包含 C 中唯一值的堆栈

c++ - 如何声明 constexpr extern?

c++ - 指向动态分配类的空指针

c++ - GCC 如何处理内置函数

templates - 为什么这个模板参数约束不起作用?

模板中的 C++ Cygwin 数字常量构建错误

c++ - 用于定义带有公开模板参数的模板结构的宏

c# - 具有通用实现的单链表

c++ - 如果其他人正在等待,是否有标准的 STL 或 Qt 方法来产生互斥量,否则保留它?

c - 使用指针在链表中排序插入,C 程序崩溃