下面的例程有望在單個鏈表開始時刪除節點,但有時會失敗。有時程序崩潰
void remove_from_front(node *start)
{
delete start;
start = start->link;
print_list(start);
}
下面的例程有望在單個鏈表開始時刪除節點,但有時會失敗。有時程序崩潰
void remove_from_front(node *start)
{
delete start;
start = start->link;
print_list(start);
}
有幾個問題我可以看到:
你解放了start
節點,然後訪問釋放的內存。這是不正確的,它會導致未定義的行爲,這意味着會發生任何事情。在一次運行中它可能會起作用,並且在下一次運行中它可能會崩潰。
你的函數需要進行更改名單的頭,但它不進行更改可見被調用的函數,因爲它不返回任何東西和參數start
按值傳遞。要解決此問題,請傳遞start
指針的地址或引用。
您的功能可能在空的列表start = NULL
上被調用。你需要處理這種情況。
正確實施:
void remove_from_front(node **start) {
// if list is empty..nothing to remove..return.
if(*start == NULL) {
return;
}
// save the address of the node following the start in new_start
node *new_start = (*start)->link;
// now delete the start node.
delete *start;
// new_start is now the new start of the list.
// And since start was passed by address, the change is reflected in the
// calling function.
*start = new_start;
}
您在刪除開始,然後嘗試通過獲取其鏈接成員來取消引用。這會因您剛刪除它而崩潰。你可能想是這樣的:
node *temp = start;
start = start->link;
delete temp;
print_list(start);
提領得到連接部件是非常非常不可能讓它崩潰。印刷更是如此。 – 2011-03-12 07:18:19
一旦你delete start
,你不能安全使用的東西用來start
指向件。這就像放下一根風箏線並希望能夠在稍後再次抓住它 - 它可能工作,但它可能不會。
這是完整的答案。 +1 – Muggen 2011-03-12 07:21:04
+1很好的解釋 – GWW 2011-03-12 07:24:00
你總是可以做一個'node * temp = * start'來使代碼更具可讀性。 – Muggen 2011-03-12 07:24:57