为双链接列表创建类的新实例

Creating a new instance of a class for a doubly linked list

本文关键字:新实例 实例 链接 列表 创建      更新时间:2023-10-16

我得到了一个用于创建双链表的启动代码。我遇到的问题是实现一个在"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释放内存。