为双链接列表创建类的新实例
Creating a new instance of a class for a doubly linked list
我得到了一个用于创建双链表的启动代码。我遇到的问题是实现一个在"head"处插入新创建的节点的函数。
链表中的一个节点是以下结构:
template <class T>
struct ListItem
{
T value;
ListItem<T> *next;
ListItem<T> *prev;
ListItem(T theVal)
{
this->value = theVal;
this->next = NULL;
this->prev = NULL;
}
};
插入头部的代码如下:
void List<T>::insertAtHead(T item)
{
ListItem<int> a(item); //create a node with the specified value
if(head==NULL)
{
head=&a; //When the list is empty, set the head
//to the address of the node
}
else
{
//when the list is not empty, do the following.
head->prev=&a;
a.next=head;
head=&a;
}
}
现在的问题是,当我插入一个项时,我应该创建一个具有不同内存地址的新类对象。我上面所做的更新了相同的内存位置。我需要知道如何创建一个新的类对象。
您所做的是错误的,并且有潜在的危险(使用指向局部变量的指针)。您需要使用new
表达式分配一个新节点:
ListItem<int>* a = new ListItem<int>(item);
当然,当完成列表时,您必须记住使用delete
释放内存。
相关文章:
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 根据参数创建派生类的新实例
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- C++ 实例化新对象时不接受继承方法默认参数值
- 实例化新类时未调用的方法
- 在 C++17 中的每个实例化时生成一个新类型
- “auto”每次创建一个新的变量实例
- cpp 中是否存在一种数据结构,可以轻松地提供一种基于已存在的实例构建新结构的方法
- 我应该始终使用shared_ptr创建类实例(而不是仅仅是新)
- 分割故障 - 遇到问题,创建新的数组实例
- 基于现有实例创建类的新实例
- 从地图访问对象会导致新对象C 的实例化
- 将unordered_map的新实例插入到unordered_map中
- 将新放置到缓冲区后,缓冲区和实例是否具有相同的 void* 地址?
- 如何自动生成结构的新实例
- 自定义容器在保留空间时不必要地创建新元素实例
- char阵列使用新的实例化后显示垃圾
- 是否为类的每个实例实例化了私有类变量
- 是否可以强制新模板实例化
- 为什么在构造函数退出时创建新的实例(对象)