我是一名C++初學者,嘗試編寫一個函數來創建C++中鏈接列表的深層副本。該函數調用自身,直到它位於源列表中的最後一個節點,然後複製該節點。但是,當我運行這個我得到一個分段錯誤或EXC_BAD_ACCESS錯誤。這是我到目前爲止:C++深度複製鏈接列表
struct node {
int data;
node* next;
};
void copy_list(const node*& source_ptr, node*& dest_ptr)
{
if (dest_ptr != nullptr){
clear_list(dest_ptr);
}
if (source_ptr == nullptr) return; //we already cleared dest_ptr
if (source_ptr->next == nullptr) // this is the last node
{
dest_ptr = new node(); //initialize in memory
dest_ptr->data = source_ptr->data; //copy the last datum
dest_ptr->next = nullptr; //since this is the end
return;
}
const node* cursor = source_ptr->next; // this happens if source is not yet at the end
copy_list(cursor, dest_ptr->next);
}
我知道還有其他類似的問題,但他們沒有幫助我。
dest_ptr = new node();
dest_ptr->data = source_ptr->data;
node* dest = dest_ptr->next;
const node* cursor = source_ptr->next;
while(cursor != nullptr)
{
dest = new() node;
dest-> data = cursor->data;
//dest->next = nullptr;
dest = dest->next;
cursor = cursor->next;
}
while循環不給錯誤,但複製是空白的(除了被外界所複製的第一個節點:我已經使用其他方法比遞歸例如while循環,看起來像也嘗試while循環)。
任何幫助,非常感謝。謝謝!
你'while'環(應優於遞歸)的問題是該行'DEST = dest->接下來;'重新覆蓋節點。 – 5gon12eder 2014-09-19 15:20:16
感謝您的評論,我可以看到您的觀點。那麼如何解決這個問題?我需要另一個變量嗎?但我不知何故必須使用一個索引變量的while循環工作,對吧? – Kiochi 2014-09-19 15:49:21