1、定义顶点数组和边集数组
在顶点数组中,下标代表边的一个顶点,存储的元素是该顶点的第一条边在边集数组中的下标。
边类有3个成员:边的另一个顶点、边的权值、顶点的下一条边的下标。
int head[max_vertex_num];
class Edge
{
public:
int to; //边的另一个顶点
int weight; //边的权值
int next; //下一条边的下标
};
Edge edge[max_edge_num];
2、边的插入函数
输入参数为边的左右结点u、v和权值w;在全局定义cnt变量作为边的下标,每次插入边之后-1.
把右结点v和权值w填入edge[cnt]中对应成员中,之后采用头插法,使其下一条边next为原来head[u]中的的元素,hend[u]改为cnt。
void InsertEdge(int u, int v, int w)
{
edge[cnt].to = v;
edge[cnt].weight = w;
edge[cnt].next = head[u];
head[u] = cnt++;
}
整体代码实现:
#include <iostream>
using namespace std;
#define max_vertex_num 10
#define max_edge_num 100
int vex_num, edge_num, cnt;
int head[max_vertex_num];
class Edge
{
public:
int to; //边的另一个顶点
int weight; //边的权值
int next; //下一条边的下标
};
Edge edge[max_edge_num];
void InsertEdge(int u, int v, int w)
{
edge[cnt].to = v;
edge[cnt].weight = w;
edge[cnt].next = head[u];
head[u] = cnt++;
}
void CreateGraph()
{
memset(head, -1, sizeof(head));
cout << "请输入顶点数:" << endl;
cin >> vex_num;
cout << "请输入边数:" << endl;
cin >> edge_num;
int u, v, w;
for (int i = 0; i < edge_num; i++)
{
cout << "请依次输入第" << i + 1 << "条边的两顶点和权值:" << endl;
cin >> u >> v >> w;
InsertEdge(u, v, w);
InsertEdge(v, u, w);
}
}
void OutputGraph()
{
for (int u = 1; u <= vex_num; u++)
{
cout << u << " ";
for (int i = head[u]; i != -1; i = edge[i].next)
{
cout << "---" << i << ":(" << edge[i].to << " " << edge[i].weight << " " << edge[i].next << ")";
}
cout << endl;
}
}
int main()
{
CreateGraph();
OutputGraph();
return 0;
}