#include<stdio.h>
#include<malloc.h>
#define INF 32767
#define MAXV 100
typedef char InfoType;
typedef struct
{
int no;
InfoType info;
}VertexType;
typedef struct
{
int edges[MAXV][MAXV];
int n,e;
VertexType vexs[MAXV];
}MatGraph;
typedef struct ANode
{
int adjvex;
struct ANode * nextarc;
int weight;
}ArcNode;
typedef struct Vnode
{
InfoType info;
int count;
ArcNode * firstarc;
}VNode;
typedef struct
{
VNode adjlist[MAXV];
int n,e;
}AdjGraph;
//----邻接矩阵的基本运算算法-----------------------
void CreateMat(MatGraph &g,int A[MAXV][MAXV],int n,int e)
{
int i,j;
g.n=n;g.e=e;
for(i=0;i<g.n;i++)
for(j=0;j<g.n;j++)
g.edges[i][j]=A[i][j];
}
void DispMat(MatGraph g)
{
int i,j;
for(i=0;i<g.n;i++)
{
for(j=0;j<g.n;j++)
if(g.edges[i][j]!=INF)
printf("%4d",g.edges[i][j]);
else
printf("%4s","∞");
printf("\n");
}
}
//----邻接表的基本运算算法-----------------------
void CreateAdj(AdjGraph * &G,int A[MAXV][MAXV],int n,int e)
{
int i,j;
ArcNode * p;
G=(AdjGraph * )malloc(sizeof(AdjGraph));
for(i=0;i<n;i++)
G->adjlist[i].firstarc=NULL;
for(i=0;i<n;j++)
for(j=n=1;j>=0;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;
}
G->n=n;G->e=n;
}
void DispAdj(AdjGraph * G)
{
ArcNode * p;
for(int i=0;i<G->n;i++)
{
p=G->adjlist[i].firstarc;
printf(" % 3d: ",i);
while (p!=NULL)
{
printf(" % 3d[ % d]→",p->adjvex,p->weight);
p=p->nextarc;
}
printf("∧\n");
}
}
void DestroyAdj(AdjGraph * &G)
{
ArcNode * pre, * p;
for(int i=0;i<G->n;i++)
{
pre=G->adjlist[i].firstarc;
if(pre!=NULL)
{
p=pre->nextarc;
while(p!=NULL)
{
free(pre);
pre=p;p=p->nextarc;
}
free(pre);
}
}
free(G);
}
//#include"graph.cpp"
int main()
{
MatGraph g;
AdjGraph * G;
int A[MAXV][MAXV]={
{0,5,INF,7,INF,INF}, {INF,0,4,INF,INF,INF},
{8,INF,0,INF,INF,9}, {INF,INF,5,0,INF,6},
{INF,INF,INF,5,0,INF}, {3,INF,INF,INF,1,0}};
int n=6,e=10;
CreateMat(g,A,n,e);
printf("(1)图G的邻接矩阵:\n");
DispMat(g);
CreateAdj(G,A,n,e);
printf("(2)图G的邻接表:\n"); DispAdj(G);
printf("(3)销毁图G的邻接表\n");
DestroyAdj(G);
return 1;
}
对存储在计算机中的数据,最基本的操作有:插入、删除、查找。
这就好比图书馆对书的管理,我们会面临的问题有:
由此类比计算机对数据进行处理,不难理解计算机解决问题的效率,与数据的组织方式密切相关。
代码功能归根结底不是别人帮自己看或讲解或注释出来的;而是被自己静下心来花足够长的时间和精力亲自动手单步或设断点或对执行到某步获得的中间结果显示或写到日志文件中一步一步分析出来的。
提醒:再牛×的老师也无法代替学生自己领悟和上厕所!
单步调试和设断点调试(VS IDE中编译连接通过以后,按F10或F11键单步执行,按Shift+F11退出当前函数;在某行按F9设断点后按F5执行停在该断点处。)是程序员必须掌握的技能之一。