【发布时间】:2013-02-07 10:59:25
【问题描述】:
我获得了用于创建双向链表的起始代码。我遇到的问题是实现一个在“头部”插入新创建的节点的函数。
链表中的一个节点是如下结构:
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;
}
}
现在的问题是,当我应该在插入项目时创建一个具有不同内存地址的新类对象时。我在上面所做的更新了相同的内存位置。 我需要知道如何创建一个新的类对象。
【问题讨论】:
-
是的,我一直在尝试。出于某种原因,我无法正确使用语法。是 ListItem a=new ListItem
? -
这不是C,我去掉了标签。
标签: c++ class linked-list