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;
}
}
現在的問題是,當我應該每當我插入一個項目時,用不同的內存地址創建一個新的類對象。我上面做的更新了相同的內存位置。 我需要知道如何創建一個新的類對象。
是的,我一直在嘗試。出於某種原因,我無法獲得正確的語法。是 ListItem a = new ListItem? –
mrsinister
這不是C,我刪除了標籤。 – unwind