2013-02-07 23 views
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; 
        } 
} 

現在的問題是,當我應該每當我插入一個項目時,用不同的內存地址創建一個新的類對象。我上面做的更新了相同的內存位置。 我需要知道如何創建一個新的類對象。

+0

是的,我一直在嘗試。出於某種原因,我無法獲得正確的語法。是 ListItem a = new ListItem ? – mrsinister

+0

這不是C,我刪除了標籤。 – unwind

回答

0

你在做什麼是錯誤的,並有潛在的危險(使用指向局部變量的指針)。你需要分配一個新的節點與new表達:

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

當然,當列表完成後,你必須記得delete釋放內存。

+0

感謝您的回答。我犯了一個非常愚蠢的錯誤。這只是我的第二個C++課程,現在我已經與編程脫節了。再次感謝。 :) – mrsinister