#include<iostream> #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define MVNum 100 //最大顶点数 using namespace std; typedef struct ArcNode {//边结点 int adjvex; //邻接点域:该边所指向的顶点的位置 int data; //数据域:存储和边相关的信息 struct ArcNode* nextarc; //链域:指向下一条边的指针 }ArcNode; typedef struct VNode {//顶点信息 int data; //顶点结点的数据域 ArcNode *firstarc; //链域:指向第一条依附该顶点的边的指针 }VNode,AdjList[MVNum]; //AdjList表示邻接表类型 typedef struct {//邻接表 AdjList vertices; int vexnum,arcnum; //图的当前顶点数和边数 }ALGragh; int CreateUDG(ALGragh &G,int vexnum,int arcnum) {//采用邻接表表示法,创建无向图G } int InsertVex(ALGragh &G) {//在以邻接表形式存储的无向图G上插入顶点v } int PrintGraph(ALGragh G) {//输出图G }补全这串代码
时间: 2023-10-21 16:03:30 浏览: 72
代码如下:
```cpp
#include<iostream>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MVNum 100 //最大顶点数
using namespace std;
typedef struct ArcNode {//边结点
int adjvex; //邻接点域:该边所指向的顶点的位置
int data; //数据域:存储和边相关的信息
struct ArcNode* nextarc; //链域:指向下一条边的指针
} ArcNode;
typedef struct VNode {//顶点信息
int data; //顶点结点的数据域
ArcNode *firstarc; //链域:指向第一条依附该顶点的边的指针
} VNode, AdjList[MVNum]; //AdjList表示邻接表类型
typedef struct {//邻接表
AdjList vertices;
int vexnum, arcnum; //图的当前顶点数和边数
} ALGragh;
int CreateUDG(ALGragh &G, int vexnum, int arcnum) {//采用邻接表表示法,创建无向图G
G.vexnum = vexnum;
G.arcnum = arcnum;
for (int i = 0; i < G.vexnum; i++) {
cout << "请输入第" << i + 1 << "个顶点的值:";
cin >> G.vertices[i].data;
G.vertices[i].firstarc = NULL; //将边表置为空表
}
for (int k = 0; k < G.arcnum; k++) {
int i, j;
cout << "请输入第" << k + 1 << "条边依附的顶点位置:";
cin >> i >> j;
ArcNode *p = new ArcNode;
p->adjvex = j - 1;
p->nextarc = G.vertices[i - 1].firstarc;
G.vertices[i - 1].firstarc = p;
p = new ArcNode;
p->adjvex = i - 1;
p->nextarc = G.vertices[j - 1].firstarc;
G.vertices[j - 1].firstarc = p;
}
return OK;
}
int InsertVex(ALGragh &G) {//在以邻接表形式存储的无向图G上插入顶点v
int v;
if (G.vexnum == MVNum) {
return ERROR;
}
cout << "请输入要插入的顶点的值:";
cin >> v;
G.vertices[G.vexnum].data = v;
G.vertices[G.vexnum].firstarc = NULL;
G.vexnum++;
return OK;
}
int PrintGraph(ALGragh G) {//输出图G
cout << "图的邻接表为:" << endl;
for (int i = 0; i < G.vexnum; i++) {
cout << "[" << i + 1 << "]" << G.vertices[i].data << " -> ";
ArcNode *p = G.vertices[i].firstarc;
while (p != NULL) {
cout << p->adjvex + 1 << " ";
p = p->nextarc;
}
cout << endl;
}
return OK;
}
int main() {
ALGragh G;
int vexnum, arcnum;
cout << "请输入无向图的顶点数和边数:";
cin >> vexnum >> arcnum;
CreateUDG(G, vexnum, arcnum);
PrintGraph(G);
InsertVex(G);
PrintGraph(G);
return 0;
}
```
阅读全文