2013-04-04 37 views
-2

我正在做一個雙向鏈表,它只存儲單個數據類型(通用),我需要它的拷貝構造函數。我以爲我知道它是正確的,但是當我測試它使用由我的教練,這不是working.When我嘗試調試它,這個問題似乎是在鏈表類的構造函數中,我只是套頭= NULL.Is這是一個正確的構造鏈接列表的拷貝構造函數

//this is the struct i am using 
struct ListItem 
{ 
    T value; 
    ListItem<T> *next; 
    ListItem<T> *prev; 

    ListItem(T theVal) 
    { 
     this->value = theVal; 
     this->next = NULL; 
     this->prev = NULL; 
    } 
}; 

template <class T> 
List<T>::List() 
{ 
    head=NULL; 
} 


template <class T> 
List<T>::List(const List<T>& otherList) 
{ 
    ListItem<T> *Headold=otherList.getHead();    
    if (Headold==NULL) 
    { 
     head=NULL; //if otherlist head is NULL,new list head=0 
    } 
    else 
    {   
     head=new ListItem<T>(Headold->value); //initializing head to the string value 

     //storing in temporary pointers 
     ListItem<T> *oldnode=Headold;  
     ListItem<T> *newnode=head; 
     while (temp->next!=NULL) 
     { 
      oldhead=oldhead->next; 
      //making new node every instance 
      newnode->next=new ListItem<T>(oldhead->next->value); 
      ListItem<T> *newnodenext=newnode->next; 
      newnodenext->prev=newnode; //setting the previous pointer of the new node 
     } 
    } 
} 
+3

爲什麼不使用調試器,並調試它? – stdcall 2013-04-04 10:49:35

+0

@Mellowcandle我正在使用Dev C++,我不熟悉它的調試器。我基本上想知道的是如果我正確地製作每個節點的副本。 – 2013-04-04 10:52:34

+2

它看起來不錯,但是stackoverflow的目的不是做代碼審查,如果你遇到特定的錯誤,或者你想要有關特定問題的信息,一般問題就好,看看這段代碼,這是行不通的,這是什麼問題是糟糕的問題... – stdcall 2013-04-04 10:54:38

回答

2

你」不更新temp1,它始終保持指向Head。 這是修復。

while (temp->next!=NULL) 
    { 
     temp=temp->next; 
     //making new node every instance 
     temp1->next=new ListItem<T>(temp->next->value); 
     ListItem<T> *temp2=temp1->next; 
     temp2->prev=temp1; //setting the previous pointer of the new node 
     temp1 = temp2; 
    } 
+0

我有一個小混合。固定 – stdcall 2013-04-04 11:07:32

+0

謝謝指出。我問的另一件事是如果構造是正確的或不是?請你回答。 – 2013-04-04 11:15:07

+0

它看起來不錯。你的意思是什麼? – stdcall 2013-04-04 11:18:25