首页 文章

为双向链表创建类的新实例

提问于
浏览
0

我已经获得了用于创建双向链表的入门代码 . 我遇到的问题是实现一个在'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;
                   }
}

现在的问题是,当我插入项目时,我应该创建一个具有不同内存地址的新类对象 . 我上面做的是更新相同的内存位置 . 我需要知道如何创建一个新的类对象 .

1 回答

  • 0

    你正在做的是错误的,并且有潜在危险(使用指向局部变量的指针) . 您需要使用new表达式分配新节点:

    ListItem<int>* a = new ListItem<int>(item);
    

    当然,完成列表后,你必须记住用 delete 释放内存 .

相关问题