加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C模板 – LinkedList

发布时间:2020-12-16 03:13:02 所属栏目:百科 来源:网络整理
导读:编辑 – 下面回答,错过了大括号.感谢所有 我一直试图写一个基本的单链表,我可以在其他程序中使用.我希望它能够使用内置和用户定义的类型,这意味着它必须是模板化的. 由于这一点,我的节点也必须被模板化,因为我不知道它将要存储的信息.我已经写了一个节点类如
编辑 – 下面回答,错过了大括号.感谢所有

我一直试图写一个基本的单链表,我可以在其他程序中使用.我希望它能够使用内置和用户定义的类型,这意味着它必须是模板化的.

由于这一点,我的节点也必须被模板化,因为我不知道它将要存储的信息.我已经写了一个节点类如下 –

template <class T> class Node
{
    T data; //the object information
    Node* next; //pointer to the next node element

public:
    //Methods omitted for brevity
};

我的链表类在单独的类中实现,并且在将新节点添加到列表的末尾时需要实例化一个节点.我已经实现了如下 –

#include <iostream>
#include "Node.h"
using namespace std;

template <class T> class CustomLinkedList
{
    Node<T> *head,*tail;

public:

    CustomLinkedList()
    {
        head = NULL;
        tail = NULL;
    }

    ~CustomLinkedList()
    {

    }

    //Method adds info to the end of the list
    void add(T info)
    {
        if(head == NULL) //if our list is currently empty
        {
            head = new Node<T>; //Create new node of type T
            head->setData(info);
            tail = head;
        }
        else //if not empty add to the end and move the tail
        {
            Node* temp = new Node<T>;
            temp->setData(info);
            temp->setNextNull();
            tail->setNext(temp);
            tail = tail->getNext();
        }
    }

    //print method omitted
};

我已经设置了以下驱动程序/测试类 –

#include "CustomLinkedList.h"
using namespace std;

int main()
{
    CustomLinkedList<int> firstList;

    firstList.add(32);
    firstList.printlist();
    //Pause the program until input is received
    int i;
    cin >> i;

    return 0;
}

我在编译时收到错误 – 错误C2955:’Node’:使用类模板需要模板参数列表 – 这指向我的add方法中的以下代码行 –

Node* temp = new Node<T>;

我不明白为什么它没有关于类型的信息,因为它在我的驱动程序类中创建时被传递给链表.我应该怎么做才能将类型信息传递给Node?

我应该创建一个私有节点结构而不是一个独立的类,并将两个类的方法组合在一个文件中?我不确定这会解决问题,但我认为可能.如果可能,我宁愿有单独的课程.

谢谢,安德鲁.

解决方法

可能想尝试
Node<T>* temp = new Node<T>;

另外,为了得到如何设计列表的提示,你当然可以看一下std :: list,尽管它有时候会变得有些尴尬.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读