#include <bits/stdc++.h>
#include "Graph.cpp"
using namespace std;
int visited[MAXV];
void DFS(ALGraph *G, int v) {
ArcNode *p;
cout << " " << v;
visited[v] = 1;
p = G->adjlist[v].firstarc;
while(p != NULL) {
if(visited[p->adjvex] == 0)
DFS(G, p->adjvex);
p = p->nextarc;
}
}
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);
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];
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);
}