向列表中添加新元素

Add new element to the list

本文关键字:元素 新元素 列表 添加      更新时间:2023-10-16

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


在过程代码中,我将创建结构,头部指针指向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,因为我想将我拥有的任何结构传递给它。所以:

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

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

在您的示例调用add(this->a);中,您将参数考虑为指向结构体的指针。

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

修改模板声明,明确T是指向的类型

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