【发布时间】:2015-10-03 22:59:50
【问题描述】:
我一直在学习链接列表的工作原理,并开始用 C++ 构建一个实现来强化这些概念。在我做了一个删除所有节点的函数之前,一切都很顺利。我想出了一个解决方案(这是注释代码),但我似乎无法弄清楚为什么其他代码不起作用。
Node 对象是使用“new”创建的类的实例。因此,'delete' 用于删除它。
我认为这可能与删除对象和重用指针变量有关。然后我遇到了这个:What happens to a pointer itself after delete? 我已经盯着它看了一段时间,试图弄清楚它可能是什么,而我研究过的任何东西似乎都没有提供答案。
到目前为止,我认为这与我的实现无关,因为在将代码替换为解决方案代码时,程序会按预期工作。
代码输出每个地址,但似乎并没有真正删除对象。如果我在 Windows 中运行程序,程序实际上会锁定并且永远不会离开 while 循环。不是无限循环,它只是卡住了,函数永远不会完成。如果我在 C4Droid 上运行它,程序不会锁定,但函数退出后节点仍然存在。
所以我的问题是,为什么当前的代码不起作用? (忽略注释的代码。这是一个可行的解决方案。)有什么简单的我忽略了指针变量?先感谢您。
void LinkedList::deleteAll() {
Node *pCurrent = pHead;
while(pCurrent){
Node *pNext = pCurrent->pNext;
std::cout << pCurrent << std::endl;
delete pCurrent;
pCurrent = nullptr;
pCurrent = pNext;
// pHead = pHead->pNext;
// delete pCurrent;
// pCurrent = pHead;
}
}
节点类
class Node{
public:
Node(string content):data(content){}
string getData(){
return data;
}
Node *pNext = nullptr;
private:
string data;
};
LinkedList.h
/*
* LinkedList.h
*
* Created on: Oct 3, 2015
* Author: Anthony
*/
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include<string>
using std::string;
class LinkedList {
public:
LinkedList();
virtual ~LinkedList();
int length();
void addNode(string nodeContent);
void deleteNode(string nodeContent);
void deleteAll();
private:
class Node{
public:
Node(string content):data(content){}
string getData(){
return data;
}
Node *pNext = nullptr;
private:
string data;
};
Node *pHead = nullptr;
};
#endif /* LINKEDLIST_H_ */
LinkedList.cpp
/*
* LinkedList.cpp
*
* Created on: Oct 3, 2015
* Author: Anthony
*/
#include "LinkedList.h"
#include <iostream>
LinkedList::LinkedList() {
// TODO Auto-generated constructor stub
}
LinkedList::~LinkedList() {
// TODO Auto-generated destructor stub
}
int LinkedList::length() {
Node *current = pHead;
int count = 0;
while(current){
count++;
current = current->pNext;
}
return count;
}
void LinkedList::addNode(std::string nodeContent) {
Node *newNode = new Node(nodeContent);
newNode->pNext = pHead;
pHead = newNode;
}
void LinkedList::deleteNode(std::string nodeContent) {
}
void LinkedList::deleteAll() {
Node *pCurrent = pHead;
while(pCurrent){
Node *pNext = pCurrent->pNext;
std::cout << pCurrent->pNext << std::endl;
delete pCurrent;
pCurrent = nullptr;
pCurrent = pNext;
// pHead = pHead->pNext;
// delete pCurrent;
// pCurrent = pHead;
}
}
main.cpp
/*
* main.cpp
*
* Created on: Oct 3, 2015
* Author: Anthony
*/
#include<iostream>
#include "LinkedList.h"
int main(int argc, char **argv){
using namespace std;
LinkedList list = LinkedList();
list.addNode(string("Test"));
list.addNode(string("Test1"));
list.deleteAll();
cout << list.length() << endl;
return 0;
}
【问题讨论】:
-
你的
Node类有析构函数吗?如果是这样,请发布它。 我已经盯着它看了一段时间 -- 使用你的调试器来调试代码。无需盯着程序。 -
@PaulMcKenzie 没有析构函数。 Node 类的代码已放在描述中。
-
我猜你在这个函数之后的某个地方堆栈(通过调试器检查它或在最后添加一些打印),只需尝试在最后(循环之后)将
pHead设置为null。 -
可能你的链表已经损坏或者在你调用函数时被错误地组合在一起。您也没有在循环后将
head指针设置为 NULL。
标签: c++ pointers linked-list delete-operator