想写一个图的十字链表,最后在析构函数里delete原先new出来的结点数组时发生断点:
#include<iostream>
using namespace std;
//十字链表
struct Edge //"边"结构体
{
int outIndex; //起点下标
int inIndex; //终点下标
Edge* front; //上一条边
Edge* next; //下一条边
};
struct Node //"结点"结构体
{
char data; //数据域
Edge* firstOut; //第一条出边
Edge* firstIn; //第一条入边
};
class Graph //"图"类
{
private:
int nodeNum; //结点数
int edgeNum; //边数
Node* myNode; //结点数组
public:
Graph(); //构造函数
//void makeNode(); //建立结点
void makeOutEdge(); //建立出边
void makeInEdge(); //建立入边
~Graph(); //析构函数
};
Graph::Graph() //构造函数的实现
{
this->myNode = NULL;
cout << "请输入结点个数:" << endl;
cin >> this->nodeNum;
cout << "请输入边的条数:" << endl;
cin >> this->edgeNum;
this->myNode = new Node[this->nodeNum];
for (int ii = 0; ii < this->nodeNum; ii++)
{
cout << "请输入第" << ii + 1 << "个结点的数据:" << endl;
cin >> this->myNode[ii].data;
this->myNode[ii].firstIn = NULL;
this->myNode[ii].firstOut = NULL;
}
}
void Graph::makeOutEdge() //出边的建立
{
int front, next; //边的起点和终点下标
Edge* temp = NULL; //temp用来临时存放new出来的边的数据
for (int ii = 0; ii < this->edgeNum; ii++)
{
temp = new Edge;
cout << "请输入第" << ii + 1 << "条边的起点和终点下标:" << endl;
cin >> front >> next;
temp->outIndex = front;
temp->inIndex = next;
temp->front = NULL;
temp->next = this->myNode[front].firstOut;
this->myNode[front].firstOut = temp; //头插法实现边的插入
}
}
void Graph::makeInEdge() //入边的实现
{
Edge* temp = NULL;
int front, next; //分别用来存放边的起点和终点下标
for (int ii = 0; ii < this->nodeNum; ii++)
{
temp = this->myNode[ii].firstOut; //temp用来接收每个结点的出边
while (temp) //只有当出边存在才执行以下命令:通过出边信息获取入边
{
front = temp->outIndex;
next = temp->inIndex; //获取边的起点和终点
//知道了起点与终点即可将该边作为终点的入边
temp->front = this->myNode[next].firstIn;
this->myNode[next].firstIn = temp; //头插法实现边的插入
temp = temp->next; //利用while循环读完每一个结点的所有出边,确保不落下任何一条边(以免有出边却没有入边的不对应情况)
}
}
}
Graph::~Graph() //析构函数的实现
{
Edge* temp1,* temp2; //用来暂时存放边
for (int ii = 0; ii < this->nodeNum; ii++) //删除创建的边
{
this->myNode[ii].firstIn = NULL;
temp1 = this->myNode[ii].firstOut;
while (temp1)
{
temp2 = temp1->next;
delete temp1;
temp1 = NULL;
temp1 = temp2;
}
this->myNode[ii].firstOut = NULL;
}
delete[] this->myNode;
this->myNode = NULL;
}
int main()
{
Graph myGraph;
myGraph.makeOutEdge();
myGraph.makeInEdge();
myGraph.~Graph();
system("pause");
return 0;
}
问题如图
求帮解