首页 文章

将新元素添加到列表中

提问于
浏览
-1

我有单链表,我想在这个结构中添加一个新元素 .


在过程代码中,我将创建结构,并将头指针指向NULL . 这是我在oo代码中解决这个问题的方法:

typedef struct a {
    int element;
    struct a *next;
} a;
typedef struct b {
    int element;
    struct b *next;
} b;

class Foo {
    a *a; // head for a structure = NULL at the beginning
    b *b; // head for b structure = NULL at the beginning

我要做的下一件事是检查列表是否为空,如果是,则设置head指向新创建的第一个元素 .

执行此操作的函数应该是模板,因为我想将任何结构传递给它 . 所以:

template <class T> void Addition_Struct::add(T head)
{
    if(head == NULL)
    {
        head = (T*)malloc(sizeof(T));

        head->next = NULL;
    }
}

此刻出现了一些问题 . 我猜T应该是结构的类型,并且头部指针(当前为NULL) . 编译器在malloc行中抛出错误 - cannot convert "a**" to "a*" . 怎么了?

编辑:

示例函数调用将是:

add(this->a);

1 回答

  • 0

    您在模板函数中混淆了 T 的含义 .

    在您的示例调用 add(this->a); 中,您正在考虑将参数设置为 pointer to a struct .

    但是你的函数 head = (T*)malloc(sizeof(T)); 认为 T 是结构类型 . 不是指针 .

    更改模板声明以阐明 T 是指向的类型 .

    template <class T> void Addition_Struct::add(T * head)
    

相关问题