0
我用C++編寫了一個鏈接列表(帶一點幫助),C++將輸入的元素從最小到最大排序。我想從相同的值中刪除多個元素,但我使用的Delete方法似乎只能刪除一個,當代碼似乎刪除更多。我嘗試使用一個調用Delete方法的循環來刪除多個元素,當它刪除一個元素時,它就成爲一個分段錯誤。我會很感激一些幫助。謝謝。刪除多個元素時出錯。刪除方法。單鏈表
void List::Append(float time, char type, int cell, long id) {
// Create a new node
Node* newNode = new Node();
newNode->SetTime(time);
newNode->SetType(type);
newNode->SetCell(cell);
newNode->SetId(id);
newNode->SetNext(NULL);
// Create a temp pointer
Node *tmp = head;
if (tmp) {
if (tmp->Time() < newNode->Time()) {
newNode->SetNext(tmp);
head = newNode;
}
else {
// Nodes already present in the list
// Parse to end of list anytime the next data has lower value
while (tmp->Next() && tmp->Next()->Time() >= newNode->Time()) {
tmp = tmp->Next();
}
// Point the lower value node to the new node
Node* _next = tmp->Next();
tmp->SetNext(newNode);
newNode->SetNext(_next);
}
}
else {
// First node in the list
head = newNode;
}
}
void List::Delete(long id) {
// Create a temp pointer
Node *tmp = head;
// No nodes
if (tmp == NULL)
return;
// Last node of the list
if (tmp->Next() == NULL) {
delete tmp;
head = NULL;
}
else {
// Parse thru the nodes
Node *prev;
do {
if (tmp->Id() == id) break;
prev = tmp;
tmp = tmp->Next();
} while (tmp != NULL);
// Adjust the pointers
prev->SetNext(tmp->Next());
// Delete the current node
delete tmp;
}
}
@WhozCraig我打算刪除一個項目,當它匹配我正在尋找的ID,然後我將它包含在一個循環內,直到它刪除所有相同的ID。 – forkfork