目录
分别以邻接矩阵和邻接表作为存储结构,实现以下图的基本操作
因为邻接矩阵和邻接表的实现原理上无太大差异,所以这里只给出邻接矩阵表示法
①增加一个新顶点v
void insertNewNode(PGraph G,int Vf,int Vl) //Vf以该顶点为弧头的边 //Vl以该顶点为弧尾的边
{
int & MaxFlag = total; //引用类型 改变MaxFLag同时改变total
G->verNums++;
G->arcNums++; //顶点和边的值都添加
if (G->verNums>total)
{
G->Vertext = lengthenArr(G,MaxFlag);
}
for (int i = G->verNums-1; i > G->verNums-2; i--)
{
G->Vertext[i].verTex = Vl;
G->Vertext[i].firstArc = NULL;
}
//链接两个顶点
int v1Index = Location(G,Vf);
int v2Index = Location(G,Vl);
ParcNode newNode = (ParcNode)malloc(sizeof(arcNode)); //新生成一个边节点
newNode->adjNode = v2Index;
newNode->nextNode = G->Vertext[v1Index].firstArc;
G->Vertext[v1Index].firstArc = newNode; //邻接点建立完成
printf("输入该边的权值\n");
scanf_s("%d",&newNode->weight);
}
④删除一条边后
void DeleteArcAndAdj(PGraph G,int Vf) //删除以Vf出发的顶点及其所有的邻接点
{
//先将Vf所有的邻接节点释放最后再将顶点节点删除
int VfIndex = Location(G,Vf);
ParcNode deleteFlag = G->Vertext[VfIndex].firstArc;
int arcFlag = 0; //删除的边数
while (deleteFlag)
{
ParcNode De = deleteFlag;
deleteFlag = deleteFlag->nextNode;
free(De); //将该节点地址删除;
arcFlag++;
}
//分支删除结束.....
//删除顶点表中的顶点
for (int i = VfIndex; i < G->verNums; i++)
{
G->Vertext[i] = G->Vertext[i+1]; //后一个节点的值覆盖前一个节点
}
G->verNums--;
G->arcNums -=arcFlag;
}
③增加一条边<v,w>
bool addNewAdj(PGraph G,int Vf,int Vl,int w)
{
//vf 要增加的边的弧尾 vl 要增加的边的弧头 w 边之间的权值
int vfIndex = Location(G,Vf);
int vlIndex = Location(G,Vl);
//判断这两个顶点是否已经存在边,如果已经存在则添加失败
if(G->Vertext[vfIndex].firstArc ==NULL)
{
printf("V%d为空,可以插入新值",Vf);
}
else
{
ParcNode judgeNode = G->Vertext[vfIndex].firstArc;
while (judgeNode&&judgeNode->weight!=w)
{
judgeNode = judgeNode->nextNode;
}
if (judgeNode->adjNode==vlIndex) //vf和vl之间存在边,直接退出
{
printf("两点之间已存在边,请重新选择两个新的节点\n");
return false;
}
}
//否则 没有新的边开始操作
ParcNode newNode = (ParcNode)malloc(sizeof(arcNode));
newNode->adjNode = vlIndex;
newNode->nextNode = G->Vertext[vfIndex].firstArc;
G->Vertext[vfIndex].firstArc = newNode;
G->arcNums++;
newNode->weight = w;
return true;
}
②删除顶点以及其附属的边
![](https://img-blog.csdnimg.cn/98437762395d4b2283871cbfc7d0075a.png)
bool delOldArc(PGraph G,int Vf,int w)
{
//Vf要删除的边依附的弧尾 w 要删除的边 通过权值来识别
int i = Location(G,Vf);
ParcNode p = G->Vertext[i].firstArc; //设置p指向第一个邻接点
if (p->weight == w)
{
G->Vertext[i].firstArc = p->nextNode; //第一个邻接点就是要删除的节点
free(p);
return true;
}
else
{
while (p->nextNode->weight!=w&&p->nextNode)
{
p = p->nextNode;
}
if(!p->nextNode)
{
return false;//没有找到相关的边
}
else //找到权值为w的上一个邻接点
{
ParcNode del = p->nextNode;
p->nextNode = del->nextNode;
free(del);
return true;
}
}
}
设计算法,实现从顶点v出发的非递归深度优先遍历
void DFS(PGraph G,int v) //从顶点v出发的深度优先遍历,非递归
{
Stack S;
Init_Stack(&S,G); //初始化栈
bool visited [10] = {}; //访问数组
int V1 = Location(G,v);
Push(&S,G->Vertext[V1]);
while (!is_empty(&S)) //栈非空
{
verNode out_node = Pop(&S); //栈头元素出栈&