有向图的十字链表表存储表示
1 //---------有向图的十字链表表存储表示------- 2 3 #include<stdio.h> 4 #include<stdlib.h> 5 6 #define MAX_VERTEXT_NUM 20 7 8 typedef int InfoType; 9 typedef char VertextType; 10 11 typedef struct ArcBox 12 { 13 int headVex; 14 int tailVex; 15 struct ArcBox *headLink; 16 struct ArcBox *tailLink; 17 InfoType *info; 18 }ArcBox; 19 20 typedef struct VexNode 21 { 22 VertextType data; 23 ArcBox *firstIn; 24 ArcBox *firstOut; 25 }VexNode; 26 27 typedef struct 28 { 29 VexNode xList[MAX_VERTEXT_NUM]; 30 int vexNum; 31 int arcNum; 32 }OLGraph; 33 34 void CreateGraphic(OLGraph *G); 35 void DisplayGraphic(OLGraph *G); 36 37 38 int main() 39 { 40 OLGraph *Graph = (OLGraph *)malloc(sizeof(OLGraph)); 41 CreateGraphic(Graph); 42 DisplayGraphic(Graph); 43 system("pause"); 44 } 45 46 void CreateGraphic(OLGraph *G) 47 { 48 int i,j,k; 49 ArcBox *arcBox; 50 printf_s("请输入顶点数和弧数:"); 51 scanf_s("%d,%d",&G->vexNum, &G->arcNum); 52 53 //建立顶点表 54 printf_s("建立顶点表\n"); 55 for (i = 0; i < G->vexNum; i++) 56 { 57 printf_s("请输入第%d个顶点:", i); 58 fflush(stdin);//刷新缓冲区 59 60 G->xList[i].data = getchar();//输入顶点值 61 G->xList [i].firstIn = NULL;//初始化指针 62 G->xList[i].firstOut = NULL;//初始化指针 63 } 64 65 //建立弧表 66 printf_s("建立弧表\n"); 67 for (k = 0; k < G->arcNum; k++) 68 { 69 printf_s("请输入(headVex-tailVex)的顶点对序号"); 70 scanf_s("%d,%d", &i, &j); 71 arcBox = (ArcBox *)malloc(sizeof(ArcBox)); 72 //对弧结点赋值 73 arcBox->headVex = j; 74 arcBox->tailVex = i; 75 arcBox->headLink = G->xList[j].firstIn; 76 arcBox->tailLink = G->xList[i].firstOut; 77 arcBox->info = NULL; 78 79 //完成在入弧和出弧链表表头的插入 80 G->xList[j].firstIn = arcBox; 81 G->xList[i].firstOut = arcBox; 82 } 83 } 84 85 void DisplayGraphic(OLGraph *G) 86 { 87 int i; 88 ArcBox *arcBox; 89 printf_s("共有%d个顶点,%d条弧\n",G->vexNum, G->arcNum); 90 91 for (i = 0; i < G->vexNum; i++) 92 { 93 printf_s("顶点%c:", G->xList[i].data); 94 95 arcBox = G->xList[i].firstIn; 96 printf_s("入度:"); 97 while (arcBox) 98 { 99 printf_s("%c->%c ", G->xList[arcBox->tailVex].data,G->xList[i].data); 100 arcBox = arcBox->headLink; 101 } 102 103 arcBox = G->xList[i].firstOut; 104 printf_s("出度:"); 105 while (arcBox) 106 { 107 printf_s("%c->%c ", G->xList[i].data,G->xList[arcBox->headVex].data); 108 arcBox = arcBox->tailLink; 109 } 110 printf_s("\n"); 111 } 112 }
请输入顶点数和弧数:4,7 建立顶点表 请输入第0个顶点:0 请输入第1个顶点:1 请输入第2个顶点:2 请输入第3个顶点:3 建立弧表 请输入(headVex-tailVex)的顶点对序号0,1 请输入(headVex-tailVex)的顶点对序号0,2 请输入(headVex-tailVex)的顶点对序号2,0 请输入(headVex-tailVex)的顶点对序号2,3 请输入(headVex-tailVex)的顶点对序号3,0 请输入(headVex-tailVex)的顶点对序号3,1 请输入(headVex-tailVex)的顶点对序号3,2 共有4个顶点,7条弧 顶点0:入度:3->0 2->0 出度:0->2 0->1 顶点1:入度:3->1 0->1 出度: 顶点2:入度:3->2 0->2 出度:2->3 2->0 顶点3:入度:2->3 出度:3->2 3->1 3->0 请按任意键继续. . .