[英]Creating a new instance of a class for a doubly linked list
I have been provided with a starter code for creating a doubly linked list. 已为我提供了用于创建双向链接列表的入门代码。 The problem I'm having is implementing a function that inserts a newly created node at the 'head'.
我遇到的问题是实现一个在'head'处插入新创建的节点的函数。
A node in the linked list is the following struct: 链表中的节点是以下结构:
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;
}
};
The code for insertion at head is as under: 插入头的代码如下:
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;
}
}
Now the problem is, when I'm supposed to create a new class object with a different memory address whenever I insert an item. 现在的问题是,每当我插入一个项目时都应该使用不同的内存地址创建一个新的类对象时。 What I'm doing above updates the same memory location.
我在上面所做的更新了相同的内存位置。 I need to know how to create a new class object.
我需要知道如何创建一个新的类对象。
What you are doing is wrong, and potentially dangerous (using pointers to local variables). 您正在做的事情是错误的,并且有潜在的危险(使用指向局部变量的指针)。 You need to allocate a new node with the
new
expression: 您需要使用
new
表达式分配新节点:
ListItem<int>* a = new ListItem<int>(item);
Of course, when done with the list, you have to remember to free the memory with delete
. 当然,完成列表后,您必须记住要使用
delete
释放内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.