代码实现:
//邻接表图
#include<iostream>
using namespace std;
const int DefaultVertices = 30;
struct Edge {
int dest; //边的另一个顶点的位置,用结构体数组的下标表示
int cost; //边的权值
Edge* link; //下一条边链指针
Edge() {
}
Edge(int num, int weight) :dest(num), cost(weight), link(NULL) {
}
};
struct Vertex {
int data; //顶点的名字
Edge* adj; //边链表的头指针
};
class Graph {
public:
Graph(int sz = DefaultVertices) {
maxVertices = sz;
numVertices = 0;
numEdges = 0;
NodeTable = new Vertex[maxVertices];
if (NodeTable == NULL) {
cerr << "存储分配失败" << endl;
exit(1);
}
for (int i = 0; i < maxVertices; i++)NodeTable[i].adj = NULL;
}
~Graph() {
for (int i = 0; i < numVertices; i++) {
Edge* p = NodeTable[i].adj;
while (p != NULL) {
NodeTable[i].adj = p->link;
delete p;
p = NodeTable[i].adj;
}