[英]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
釋放內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.