邻接表(数组与链表相结合的存储方法)的结构类似于树的存储–孩子表示法。
#include
typedef struct FNode{
char data;
struct DNodefirstedge; //firstedge指向边表的第一个节点
}FNode;
typedef struct DNode{
int adjvex; //边表结点的内容
int weight; //权
DNodenext;
}DNode;
class AlGraph{
public:
AlGraph();
~AlGraph();
public:
AlGraph(const size_t&a, const size_t&b) :numVertexes(a), numEdges(b){ CreatAlGraph(); };
void traverse(); //遍历
private:
static const size_t Maxsize = 100;
FNode fnode[Maxsize]; 顶点表结构体数组
const size_t numVertexes = 0; //图中顶点数
const size_t numEdges = 0; //图中边数
void CreatAlGraph(); //创造一个邻接表
};
void AlGraph::CreatAlGraph()
{
char ch;
int ai,bj;
for (int i = 0; i < numVertexes; ++i)
{
std::cout << “please enetr Vertex information:”;
std::cin >> ch;
fnode[i].data = ch; //初始化顶点的内容
fnode[i].firstedge = nullptr; //初始化顶点表的指针
}
for (int j = 0; j < numEdges; ++j)
{
std::cout << "please enetr (Vi,Vj)" << "\n";
std::cin >> ai>>bj;
DNode*e = new DNode;//创建一个边表结点(向内存中申请空间)
e->adjvex = j; //邻接序号为j;
e->next= fnode[j].firstedge; // 将e指针指向当前顶点指向的结点 (类似创建链表中的头插法);
fnode[j].firstedge = e; //将当前顶点的指针指向e;
DNode*s = new DNode;
s->adjvex = i;
s->next = fnode[i].firstedge;
fnode[i].firstedge = s;
}
}
void AlGraph::traverse()
{
DNodee;
for (int i = 0; i < numVertexes; ++i)
{
e = fnode[i].firstedge;
if(e->next != nullptr)
{
std::cout << e->adjvex << " " << e->weight;
e = e->next;
}
}
}
AlGraph::~AlGraph()
{
DNodee;
for (int i = 0; i < numVertexes; ++i)
{
e = fnode[i].firstedge;
if (e)
{
delete e;
e = e->next;
}
}
}
int main(int argc, char**argv)
{
const size_t numvertexes = 4;
const size_t numedges = 5;
AlGraph algraph(numvertexes, numedges);
algraph.traverse();
return 0;
}