2013-08-18 85 views
0

我正在用C++編寫一個函數來將「int」類型的「數據」添加到鏈表的末尾。C++中鏈接列表實現中的分段錯誤

void insert_back() 
{ 
int no; 
node *temp; 
cout<<"\nEnter the number"<<"\n"; 
cin>>no; 
temp = head; 
if(temp != NULL) 
{ 
     while(temp != NULL) 
        temp = temp->next; 
} 

temp->next = (node*)malloc(sizeof(node)); 
temp = temp->next; 
temp->data = no; 
temp->next = NULL; 

}

然而,在該行,TEMP->下一=(節點*)malloc的(的sizeof(節點)),我得到訪問衝突錯誤(分段錯誤)。我沒有發現任何根本錯誤。你可以在這個問題上給我啓發嗎?

+0

它不進入循環。而是一個新的節點被初始化,它被temp指向。我的主要鏈表是「list」,所以實際上我需要給出一個聲明:list = temp;在函數結束時。 –

回答

-1
while(temp != NULL) 
    temp = temp->next; 

上面的代碼讓你到列表中的最後一個節點。因此,您應該將節點添加到temp本身,而不是temp->next

temp = (node*)malloc(sizeof(node)); 

現在最後一個節點的子節點應該是NULL。

temp->next = NULL; 
+1

這個新的'temp'將沒有連接到列表,所以爲什麼要打擾循環? – Beta

+0

我在這裏有一個疑問.. temp-> next給出下一個節點的地址。那麼新節點應該由temp-> next引用而不是temp? –

+0

此外,'temp'指向最近分配的內存區域。你確定你想把它當作一個'node'嗎?使用C++方法有真正的優勢。 – Beta

0

就在該行執行之前,temp將爲空。然後,您將其解除引用。

1

如果你想獲得列表的最後一個節點,只是檢查是否下一個成員爲空或不作爲最後一個節點的下一個成員爲空。

在你的代碼中,你檢查temp爲空或不是temp-> next

while(temp != NULL) 
    temp = temp->next; 

當循環結束時將得到temp爲空。

此外,您還應該考慮頭部爲空的情況。

void insert_back() 
{ 
    int no; 
    node *temp; 
    cout<<"\nEnter the number"<<"\n"; 
    cin>>no; 
    temp = head; 
    if(temp != NULL) 
    { 
     while(temp->next != NULL) 
      temp = temp->next; 
     temp->next = (node*)malloc(sizeof(node)); 
     temp = temp->next; 
     temp->data = no; 
     temp->next = NULL; 
    }else{ 
     head = (node*)malloc(sizeof(node)); 
     head->data = no; 
     head->next = NULL; 
    } 

} 
+1

'if(temp!= NULL)'沒有幫助 –

+0

我剛剛沒注意到。我認爲我沒有考慮頭部無效的情況,你的意思是? – ningyuwhut

+0

是的,看起來你現在已經處理了。 +1 –