我想在列表的第n個位置刪除單個鏈接列表中的節點,但在運行項目時我一直收到一個分段錯誤:11。下面是我的功能remove
我認爲問題是,但我似乎無法弄清楚爲什麼它不工作,因爲邏輯是有道理的。另外,其中headM
點在列表中的第一個項目中是第0個位置。 我打這個電話之前刪除我的名單順序770 440 330 220 110
我兩次調用刪除在C++中刪除鏈接列表中的節點
remove(0)
remove(2)
名單應該是440 330 110
後,但現在我得到770 330 110
....
void SimpleList::remove(int n)
{
if(n < 0 || n > sizeM) {
return;
}
Node* p = headM;
for(int c = 0; c < n - 1; c++)
{
p = p->next;
//assert(p != nullptr);
}
Node* const p_doomed = p->next;
//assert(p_doomed != nullptr);
p->next = p_doomed->next;
delete p_doomed;
--sizeM;
}
下面是節點的結構。這部分是正確的,因爲我的push_front
和push_back
工作。
class Node {
public:
ListItem item;
Node *next;
};
Node *headM;
int sizeM;
void destroy();
// Deallocate all nodes, and sets headM to zero.
void copy(const SimpleList& source);
// List becomes copy of source.
你考慮重新設計和使用的std ::名單?這會節省時間。 – harper 2014-12-02 09:44:57