邻接多重表
能不能只出现一次呢?
#include<iostream>
#define OK 1
#define ERROR 0
#define FALSE 0
#define TRUE 1
#define MAXNum 100
using namespace std;
/*
为啥要邻接多重表呢?
一开始的那个邻接表有啥问题呢,就是在存无向图的时候吧
它每条边都会存两次,
因为它的边结点的类型是data+firstedge(指向依附于该顶点的边)
然后我们把它修改一下:
mark+ivex+ilink+jvex+jlink+info
mark:标记这个边是否被搜索过
ivex:该边依附的两个顶点在表头数组中的位置
ilink:指向依附于ivex的下一条边
jvex:该边依附的两个顶点在表头数组中的位置
jlink:指向依附于jvex的下一条边
info:其他信息
*/
typedef int Status;
typedef char VerTexType;
typedef int OtherInfo;
//定义边结点的类型
typedef struct ArcNode {
int mark;
int ivex;
ArcNode* ilink;
int jvex;
ArcNode* jlink;
OtherInfo info;//这里是为了创建无向图的时候保存权重的时候使用,这里没有用
};
//定义表头结点类型
typedef struct VNode {
VerTexType data;
ArcNode* first;
}VNode,AdjList[MAXNum];
//定义图的类型
typedef struct ALGraph {
AdjList vertices;//定义邻接多重表
int vernum, arcnum;//总结点数和总边数
}ALGraph;
//查找结点数据x在邻接表中处于什么位置
int Locate(ALGraph G, VerTexType x) {
for (int i = 0; i < G.vernum; i++) {
if (G.vertices[i].data == x) {
return i;
}
}
return -1;
}
Status create(ALGraph& G) {
cout << "请输入总结点数和总边数:" << "\n";
cin >> G.vernum >> G.arcnum;
cout << "\n请依次输入各个顶点的数据:" << "\n";
for (int i = 0; i < G.vernum; i++)
{
//构造定点表
cin >> G.vertices[i].data;
G.vertices[i].first = NULL;
}
cout << "\n请输入每条边的数据:(顶点1 顶点2 )\n";
for (int x = 0; x < G.arcnum; x++)
{
VerTexType i, j;
cin >> i >> j;
int ivex = Locate(G, i);
int jvex = Locate(G, j);
ArcNode* p=new ArcNode;
p->ivex = ivex;
p->jvex = jvex;
//将这个结点插入到顶点表中下标为ivex中的链表后面
p->ilink = G.vertices[ivex].first;
G.vertices[ivex].first = p;
//将jlink指针域链接到jvex链表后面
p->jlink = G.vertices[jvex].first;
G.vertices[jvex].first = p;
}
return OK;
}
void outPut(ALGraph G) {
for (int i = 0; i < G.vernum; i++)
{
printf("\n顶点%c相连的边为:\n", G.vertices[i].data);
VerTexType x = G.vertices[i].data;
ArcNode* p = G.vertices[i].first;
while (p)
{
printf(" 边:%c %c", G.vertices[p->ivex].data, G.vertices[p->jvex].data);
if (G.vertices[p->ivex].data == x) {//这里和下面的==号写成=号还不报错,导致我debug了一个小时,5555
p = p->ilink;
}
else if (G.vertices[p->jvex].data == x)
{
p = p->jlink;
}
}
}
}
int main() {
ALGraph G;
create(G);
outPut(G);
return 0;
}