2014-09-23 99 views
-2

我的程序正在編譯,但是當我嘗試運行此代碼時,我收到了seg錯誤。我想要做的是將一個元素附加到鏈表的末尾。這裏是我的應用程序是這樣做的:分割錯誤鏈接列表C++插入末尾

int main() 
{ 
    linklist<int> l; 
    int i = 30; 
    l.insertEnd(i); 
    return (0); 
} 

這裏是從我的類函數的實現:

template <class T> 
void linklist<T>::insertEnd(T anItem) 
{ 
    if(this->headPointer = NULL) 
    { 
     headPointer = new node(anItem, NULL); 
    } 
    else 
    { 
    node* endPointer = headPointer; 
    while(endPointer->linkPointer != NULL) 
    { 
     endPointer = endPointer->linkPointer; 
    } 
    endPointer->linkPointer = new node(anItem, NULL); 
    } 
}; 

最後,這裏是我的節點是如何設置的:

class node 
    { 
    public: 
    T dataItem; 
    node* linkPointer; 
    // construct a new node and initialize its attributes with the given parameters. 
    node(T i, node* l): dataItem(i), linkPointer(l) 
    { 
    }; 
    }; 
    node* headPointer;  
}; 
+1

你等號應該是一個比較操作。 – 0x499602D2 2014-09-23 04:11:44

+1

你的問題其實是值得的嗎? – 2014-09-23 04:15:43

回答

2

它看起來像這個聲明中的問題,在這裏,而不是比較你分配。

if(this->headPointer = NULL) 

使用此:

if(this->headPointer == NULL) 

if(NULL == this->headPointer) // This is better way to compare. 
3
template <class T> 
void linklist<T>::insertEnd(T anItem) 
{ 
    if(this->headPointer == NULL) //you were assigning null instead of comparing 
    { 
     headPointer = new node(anItem, NULL); 
    } 
    //rest of the code here 

試試這個

+0

從下次在發佈問題之前做一些分析 – 2014-09-23 04:17:18

+0

我欣賞的幫助,但我花了超過4個小時在這一點上花費了。我不知道'='甚至可能是一個問題。它正在編譯,只是沒有運行。 – RMK 2014-09-23 04:22:17

+0

是的,畢竟這是一臺電腦。完善編碼是必要的。 – 2014-09-23 04:25:34