实现功能:
1. 无向图邻接表实现
算法说明:
分别输入无向图边和结点的信息,用指针来构建不同链表之间的联系。
源代码:
#include <iostream>
using namespace std;
#define NUM 20
struct arcnode
{
int adjvex;
struct arcnode *nextarc;
};
typedef struct vnode
{
char data;
arcnode *firsttarc;
}vnode, adjlist [NUM];
typedef struct algraph
{
adjlist vertices;
int vexnum, arcnum;
}algraph;
algraph G;
int visited [20];
void init ()
{
int a;
cout << "是否开始创建新的邻接表?" ;
cin >> a;
while (a != 0)
{
//algraph G;
cout << "输入顶点个数:" ;
cin >> G.vexnum;
cout << "输入弧的个数:" ;
cin >> G.arcnum;
}
}
void get_vex ()
{
cout << "————————————输入全部顶点信息————————————" ;
for (int i = 0; i < G.vexnum; i ++)
{
cout << "第" << i << "个顶点:" ;
cin >> G.vertices[i].data;
G.vertices[i].firstarc = NULL;
}
}
void get_arc ()
{
char v1, v2;
int v1locate, v2locate;
arcnode *p, *q;
cout << "——————————输入每条弧两端的顶点位置——————————" ;
for (int i = 1; i <= G.arcnum; i ++)
{
cout << "第" << i << "条弧:" ;
cin >> v1 >> v2;
v1locate = locate (G, v1);
v2locate = locate (G, v2);
p = new arcnode;
p -> adjvex = v2locate;
p -> nextarc = G.vextices [v1locate].firstarc;
G.vextices [v1locate].firstarc = p;
q = new arcnode;
q -> adjvex = v1locate;
q -> nextarc = G.vextices [v2locate].firstarc;
g.vextices [v2locate].firstarc = q;
}
}
int locate (algraph G, int x)
{
int i = 0;
while (i < G.vexnum && x != G.vertices[i].data) i ++;
return i;
}
void dfs (algraph G, int vex)
{
visited [vex] = 1;
cout << G.vertices[vex].data << " " ;
for (arcnode *p = G.vertices[vex].firstarc; p; p = p -> nextarc)
{
if (!visited [p -> adjvex])
{
dfs (G, p -> adjvex);
}
}
}
int main ()
{
init ();
get_vex ();
get_arc ();
cout << "从哪个位置开始遍历(深度遍历):" ;
int n;
cin >> n;
dfs (G, n);
return 0;
}
2. 有向图邻接表
只要修改图中代码get_arc()片段即可,具体做法:去掉arcnode *q指针及该指针的所有使用即可。