C++ 将新元素添加到列表中
我有一个单链表,我想在这个结构中添加一个新元素C++ 将新元素添加到列表中,c++,C++,我有一个单链表,我想在这个结构中添加一个新元素 在过程代码中,我将创建结构,并创建指向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 a
在过程代码中,我将创建结构,并创建指向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
的含义
在示例调用中add(this->a)代码>,您将该参数视为指向结构的指针
但是你的函数head=(T*)malloc(sizeof(T))
将T
视为结构类型。不是指针
更改模板声明以澄清T
是指向的类型
template void Addition\u Struct::add(T*head)
当你使用C++时,为什么要标记它“C”。为什么你使用<代码> Malc C++ >代码>而不是‘新’?你调用的是什么?>代码>转换堆栈?是的,我完全忘记改变我的代码-编辑,对不起。@ ED愈合-因为我必须在C中写东西,但是使用C++类。@ USE22527 86-如果你可以使用C++,然后使用新的。无论哪种方式,你都要对你正在使用的语言下定决心。
add(this->a);
template <class T> void Addition_Struct::add(T * head)