C++ _递归删除链表后,块类型无效(pHead->nBlockUse)错误
我已经成功地实现了递归打印列表方法,所以我不明白为什么递归析构函数不能工作:C++ _递归删除链表后,块类型无效(pHead->nBlockUse)错误,c++,pointers,recursion,visual-studio-2013,linked-list,C++,Pointers,Recursion,Visual Studio 2013,Linked List,我已经成功地实现了递归打印列表方法,所以我不明白为什么递归析构函数不能工作: //recursively deleting nodes in a doubly linked list LinkedList::~LinkedList() { if (Head == 0) //base case { Tail = 0; //fixing the dangling Tail pointer doesn't seem to fix the error...
//recursively deleting nodes in a doubly linked list
LinkedList::~LinkedList()
{
if (Head == 0) //base case
{
Tail = 0; //fixing the dangling Tail pointer doesn't seem to fix the error...
return;
}
else
{
Node* temp = Head;
Head = Head->getNext();
cout << "deleting " << temp->getNumber() << endl;
delete temp;
delete this;
}
}
删除这就是问题所在。您的LinkedList类不是使用new创建的,因此不需要删除它。0x499602D2:1。如果不删除此项,您认为我如何进行递归调用?2.即使我用new创建了我的LinkedList,当我删除它时,我也会得到同样的错误,就像我在帖子中说的那样,如果我不删除,就不会有错误it@YiboYang-请发布节点类。此处不需要递归。您需要一个while循环,只要Head不为null,它就会继续循环。@YiboYang-while Head!=空移除头;如果您有一个从链表中删除单个节点的remove函数,那么这就是您的代码实际上需要做的全部工作。
//Specification file for BaseNode class
#ifndef BASENODE_H
#define BASENODE_H
#include <iostream>
class BaseNode
{
protected:
char * name;
int number;
BaseNode * next;
public:
//default constructor
BaseNode();
//overloaded constructor
BaseNode(const char *, int);
//destructor
~BaseNode() {
std::cout << "name is: " << name << '\n';
delete[] name;
}
//getter functions
char * getName() const { return name; }
int getNumber() const { return number; }
BaseNode* getNext() { return next; }
//setter functions
void setNumber(int num){ number = num; };
void setNext(BaseNode* ptr) { next = ptr; }
};
#endif
//Implementation file for BaseNode class
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <cstring>
#include "BaseNode.h"
//default constructor
BaseNode::BaseNode()
{
name = 0;
number = 0;
next = 0;
}
//overloaded constructor
BaseNode::BaseNode(const char * str, int num)
{
roman = new char[strlen(str) + 1]; //set aside one more character for null terminator
strcpy(name, str);
number = num;
}
#ifndef Node_H
#define Node_H
#include "BaseNode.h" //include the base class for inheritance to work
class Node : public BaseNode
{
protected:
Node * prev;
Node * next;
public:
Node() : BaseNode()
{ prev = next = 0; }
Node(const char * namestr, int num) : BaseNode(namestr, num)
{ prev = next = 0; }
//empty destructor; the BaseNode destructor automatically gets called from here and does the job
~Node() { }
//getter functions and setter functions are all inherited from BaseNode, except that....
//the BaseNode version of getNext and setNext won't work for our Node class
Node* getNext() const { return next; }
void setnext(Node* pointer) { next = pointer; }
Node* getPrev() const { return prev; }
void setPrev(Node* pointer) { prev = pointer; }
};
#endif