【发布时间】:2014-10-25 07:10:57
【问题描述】:
我现在正在尝试学习 C++,因为我将不得不参加一门课程,而且我来自 Java。我目前正在阅读“Jumping into C++”一书并完成练习。在阅读了关于链表的部分后,它告诉我创建自己的链表并拥有一个删除元素的方法(在练习中使用指针)。
到目前为止,我已经能够向我的链表添加值,并显示我的链表。在执行我的删除元素方法后,让我的程序明确告诉我它已删除特定内存地址处的值,我再次显示列表以发现我的值仍然以某种方式出现在据称已被删除的内存地址处。
这是我的 removeElement 方法:
// remove an element from the linked list
void removeElement(int remValue) {
// to remove an element, we go through the list, find the value given
// if we find it, stop
// to remove, disconnect the link
// relink the two values now (ie. value 1->2->3->NULL, 2 is removed, 1->3->NULL )
LinkedList* current = head;
LinkedList* next = current;
while(current != NULL) {
if(current->value == remValue) { // if match
break; // break out of while
}
else {
cout << "Value " << current->value << " does not match " << remValue << ".\n";
next = current; // save in case
current = current->pNextValue; // go to next value
}
} // end while
if(current == NULL) { // if we reached end of list
cout << "Can't remove value: no match found.\n"; // no match, cant remove
} else { // found match
cout << "Deleting: " << current << "\n";
delete current;
current = next->pNextValue; // current is updated
}
}
这是我的链表的全部代码(包括一些测试以查看内容的去向):
我意识到我的大部分代码对于一个现实的链表来说效率不高,也不正常,我只是想弄清楚指针以及如何在最基本的链表中使用它们。
【问题讨论】:
-
附带说明,在现代 C++ 中,您并不真正需要
delete(在 C++14 中也不是真正需要new),因此您可能想找到更现代的 C++学习资料...
标签: c++ list pointers linked-list