数据结构(图)HD201801
把一件事做好,做简单,就是对自己最好的一份靠赏.
今天把建图的代码自己模拟了一下,是使用领接表写的,产出量太低,明天来写图的两个遍历算法吧.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define MAXVERTEXNUM 6 //图的顶点数
#define MAXARCNUM 7 //图的弧数
void createGraph(); //建立图
void deleteGraph(); //删除图,释放内存
void DFS(); //深度优先
void BFS(); //广度优先
void PrintGraph(); //打印图
//边表
typedef struct ArcNode
{
int adjvex; //该弧所指向的顶点的位置
struct ArcNode *next; //指向下一条弧的指针
ArcNode(int a)
{
this->adjvex = a;
}
} ArcNode;
//顶点表
typedef struct VNode
{
int data;
// int num;
ArcNode *first;
} VNode;
//领接表
typedef struct ALGraph
{
int vexnum; //图的顶点数
int arcnum; //图的弧数
ALGraph(int v, int a)
{
this->vexnum = v;
this->arcnum = a;
}
} ALGraph;
//建立一个图
ALGraph G(MAXVERTEXNUM, MAXARCNUM);
//建立顶点表
VNode AdjList[MAXVERTEXNUM];
//初始化顶点表(在顶点表后面加入边表结合)
void createGraph(ALGraph &G, VNode (&AdjList)[MAXVERTEXNUM])
{
int i;
printf("依次输入顶点表结点");
for (i = 0; i < G.vexnum; ++i)
{
//输入顶点表结点
scanf("%d", &AdjList[i].data);
}
//处理边表结点
for (i = 0; i < G.vexnum; ++i)
{
//依次处理每个顶点表的结点
int n = 0;
int input = 0;
printf("please input node(%d)'s edge-nodes num\n", (i + 1));
scanf("%d", &n);
if (n == 0)
{
continue;
}
printf("please input edge-nodes one by one\n");
scanf("%d", &input);
n--;
ArcNode *arc = new ArcNode(input);
AdjList[i].first = arc;
while (n > 0)
{
scanf("%d", &input);
ArcNode *temp = new ArcNode(input);
arc->next = temp;
arc = arc->next;
n--;
}
}
printf("---------------------------------------------------\n");
}
void deleteGraph(ALGraph &G, VNode (&AdjList)[MAXVERTEXNUM])
{
//这个函数很简单,删除所有结点与指针,释放内存空间即可
for (int i = 0; i < G.vexnum; ++i)
{
if (AdjList[i].first)
{
delete[] AdjList[i].first;
}
}
printf("delete OK");
}
void PrintGraph()
{
for (int i = 0; i < G.vexnum; ++i)
{
printf("node(%d)'s information\n", (i + 1));
printf("node number is %d\t", AdjList[i].data);
printf("the edge-nodes contains\n");
ArcNode *temp = AdjList[i].first;
while (temp != NULL)
{
printf("%d", temp->adjvex);
temp = temp->next;
}
printf("\n");
}
}
int main(int argc, char const *argv[])
{
createGraph(G, AdjList);
PrintGraph();
deleteGraph(G, AdjList);
return 0;
}