邻接表2 -试在邻接表存储结构上实现图的基本操作 del_vertex-数据结构-图-icoding
生活随笔
收集整理的這篇文章主要介紹了
邻接表2 -试在邻接表存储结构上实现图的基本操作 del_vertex-数据结构-图-icoding
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
鄰接表2
試在鄰接表存儲結構上實現圖的基本操作 del_vertex,相關定義如下:
typedef int VertexType;typedef enum{DG, UDG }GraphType;typedef struct ArcNode{int adjvex;InfoPtr *info;struct ArcNode *nextarc; }ArcNode;typedef struct VNode{VertexType data;ArcNode *firstarc; }VNode; typedef struct{VNode vertex[MAX_VERTEX_NUM];int vexnum, arcnum;GraphType type; }ListGraph;int locate_vertex(ListGraph *G, VertexType v); //返回頂點 v 在vertex數組中的下標,如果v不存在,返回-1 bool del_vertex(ListGraph *G, VertexType v); //刪除頂點 vAttention: 判斷條件如下:
當成功刪除頂點或邊時,函數返回true,否則(如頂點或邊不存在、刪除邊時頂點v或w不存在)返回false。
參考代碼如下:
//注意的一點是free函數包含在頭文件<stdlib.h>中
#include <stdio.h> #include <stdlib.h> #include "graph.h" //請勿刪除,否則檢查不通過 bool del_vertex(ListGraph* G, VertexType v) {int i, j;ArcNode* p, *q;j = locate_vertex(G, v);if (j == -1) return false; q = G->vertex[j].firstarc;if(q){//q存在出度 for(p = q->nextarc; p != NULL; p = q->nextarc){q->nextarc = p->nextarc;free(p);G->arcnum--;}//刪除結點直接鏈接出去的邊結點, 表頭結點最后循環完單獨刪除free(q);//刪除表頭結點 G->vertex[j].firstarc = NULL;G->arcnum--;}G->vexnum--;//再刪除到該節點的邊for (i = 0; i < G->vexnum; i++) {p = G->vertex[i].firstarc;pNode = NULL;while (p) {if (p->adjvex == j) { //P的下個結點是Vif (!pNode) { //P是表頭結點q = G->vertex[i].firstarc;//方便最后統一free G->vertex[i].firstarc = p->nextarc;}else {pNode->nextarc = p->nextarc;q = p;}free(q);G->arcnum--;break;//這個鏈表后面不可能還有邊 (對于頂點v的入度)} else {pNode = p;p = p->nextarc;}}}return true; }//另外, 對于后半部分的free掉對于頂點v的入度, 我感覺icoding有問題, 另解如下, 歡迎大佬指正!!
#include <stdio.h> #include <stdlib.h> #include "graph.h" //請勿刪除,否則檢查不通過 bool del_vertex(ListGraph* G, VertexType v) {int i, j;ArcNode* p, *q;j = locate_vertex(G, v);if (j == -1) return false; q = G->vertex[j].firstarc;if(q){//q存在出度 for(p = q->nextarc; p != NULL; p = q->nextarc){q->nextarc = p->nextarc;free(p);G->arcnum--;}//刪除結點直接鏈接出去的邊結點, 表頭結點最后循環完單獨刪除free(q);//刪除表頭結點 G->vertex[j].firstarc = NULL;G->arcnum--;}G->vexnum--;for (i = j; i < G->vexnum; i++) { //表頭結點中,后面的向前移動G->vertex[i] = G->vertex[i + 1];}for(i = 0; i < G->vexnum; i++){q = G->vertex[i].firstarc;if(q){if(q->adjvex == v){//q為表頭 G->vertex[i].firstarc = q->nextarc;free(q);G->arcnum--;continue;}for(p = q->nextarc; p!=NULL;q = p, p = p->nextarc){if(p->adjvex == v){q->nextarc = p->nextarc;free(p);G->arcnum--;break;}}}}return true; }歡迎討論區交流哦!
總結
以上是生活随笔為你收集整理的邻接表2 -试在邻接表存储结构上实现图的基本操作 del_vertex-数据结构-图-icoding的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果平板ipad的无法连接无线网络WiF
- 下一篇: MATLAB-矩阵基本语法知识