#include <bits/stdc++.h>
#include "Graph.cpp"
using namespace std;
int visited[MAXV];
void DFS(ALGraph *G, int v) { // 邻接表的DFS算法
ArcNode *p;
cout << " " << v;
visited[v] = 1;
p = G->adjlist[v].firstarc; // p指向顶点v的下一个邻接点
while(p != NULL) {
if(visited[p->adjvex] == 0)
DFS(G, p->adjvex); // 若p->adjvex顶点未访问,递归访问它
p = p->nextarc; // p指向顶点v的下一个邻接点
}
}
int main() {
ALGraph *G;
int A[][MAXV]= {
{0,1,0,0,1},
{0,0,1,1,1},
{0,0,0,0,0},
{0,0,1,0,1},
{0,0,0,0,0}
};
int n=5,e=7;
CreateAdj(G, A, n, e); //创建图的邻接表存储结构G
cout << "图的邻接表如下:" << endl;
DispAdj(G);
cout << "图的邻接表的深度优先遍历如下:" << endl;
DFS(G, 0);
return 0;
}
#include <bits/stdc++.h>
#define MAXV 50 // 最大顶点个数
#define MAXL 20
#define INF 0x3f3f3f3f //表示∞
using namespace std;
typedef struct ANode {
int adjvex; // 该边的终点编号
int weight; // 改变的权值
struct ANode *nextarc; //指向下一条边的指针
} ArcNode; // 边结点的类型
typedef struct Vnode {
char data[MAXL]; // 顶点信息
ArcNode *firstarc; // 指向第一条边
} VNode; // 邻接表的表头的结点类型
typedef VNode AdjList[MAXV]; // AdjList是邻接表类型
typedef struct {
AdjList adjlist; // 邻接表
int n, e; // 图中的顶点数和边数
} ALGraph; // 图
void CreateAdj(ALGraph *&G, int A[][MAXV], int n, int e) { //建立图的邻接表
ArcNode *p;
G = (ALGraph *) malloc (sizeof(ALGraph));
G->n = n;
G->e = e;
for(int k = 0; k < n; k++)
G->adjlist[k].firstarc = NULL;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
if(A[i][j] != 0 && A[i][j] != INF) {
p = (ArcNode *) malloc (sizeof(ArcNode));
p->adjvex = j;
p->weight = A[i][j];
p->nextarc = G->adjlist[i].firstarc;
G->adjlist[i].firstarc = p;
}
}
void DispAdj(ALGraph *G) {
ArcNode *p;
for(int i = 0; i < G->n; i++) {
cout << i;
p = G->adjlist[i].firstarc;
while(p != NULL) {
cout << "->" << "结点编号:" << p->adjvex << " 边的权值:" << p->weight;
p = p->nextarc;
}
cout << "^" << endl;
}
}
void DestroyAdj(ALGraph *&G) { // 销毁图的邻接表
ArcNode * pre ,*p;
for(int i = 0; i < G->n; i++) {
pre = G->adjlist[i].firstarc;
while(pre != NULL) {
p = pre->nextarc;
free(pre);
pre = p;
}
}
free(G);
}