0
我寫了這個函數,將另一個鏈表插入到現有鏈表中。當我輸出函數中的「this」對象的值時,輸出是正確的。但是,程序在最後調用析構函數時會遇到運行時錯誤。我認爲運行時錯誤是由於有2個指針指向相同的地址造成的;因此當一個人被分配時,另一個人成爲懸掛指針。在鏈表中插入一個鏈表
有什麼辦法可以插入另一個鏈接列表到現有的鏈接列表(在中間),而不會導致這個問題?
void List::insert(const List& otherList, const int &index)
{
Node* insertion = head;
int x = index;
while (x > 0){
insertion = insertion->next;
x--;
}
if (index == 0){ //this works fine
otherList.tail->next = insertion;
*this = otherList; /*I implemented a copy ctor
that performs deep copy
so this is also fine */
}
else{ // this block causes problems
Node* tmp = insertion->next;
insertion->next = otherList.head;
otherList.tail->next = tmp;
}
cout << "after the copy\n" << (*this) << endl;
}
插入後,這兩個列表引用相同的節點,這就是爲什麼你的代碼崩潰。一個析構函數釋放共享節點,然後另一個析構函數嘗試再次釋放它們。您需要從源列表中物理刪除節點,以使它們僅存在於目標列表中,否則您需要深度複製節點的* data *並且不要複製節點指針本身。 –
@Remy,我如何刪除源列表,因爲它是通過常量引用傳遞的...我無法修改它 –
因此,在這最後,你應該有兩個列表 - 一個列表是兩個列表的連接,第二個列表沒有修改?這在你的問題中並不清楚。如果第二個列表沒有被修改,爲什麼不寫一個簡單的循環,爲傳入的列表中的每個節點調用(this hope to you coded it)'this-> insertNode()'或類似的函數? – PaulMcKenzie