參考:《大話數據結構》
鄰接表的缺陷:不能同時關注出度和入度
十字鏈表:
(1)頂點表
firstin表示入邊表頭指針,指向該頂點的入邊表中的第一個結點;firstout表示出邊表頭指針,指向該頂點的出邊表中的第一個結點。
(2)邊表結點
tailvex是弧起點在頂點表中的下標;headvex是弧終點在頂點表中的下標;headlink是指入邊表指針域,指向終點相同的下一條邊;taillink是指出邊表指針域,指向起點相同的下一條邊。如果是網還可以增加一個weight域來存儲權值。
.h文件
#pragma once #define MAXVEX 20 typedef char VertexType; //頂點類型應由用戶定義 typedef int EdgeType; //邊上的權值類型應由用戶定義 typedef struct EdgeNode //邊表結點 { int tailvex; int headvex; EdgeType weight; struct EdgeNode *headlink; struct EdgeNode *taillink; }EdgeNode; typedef struct VertexNode //頂點表結點 { VertexType data; EdgeNode *firstin; //入邊表頭指針 EdgeNode *firstout; //出邊表頭指針 }VertextNode, CrossList[MAXVEX]; typedef struct { CrossList adjList; int numVertexes, numEdges; //圖中當前頂點數和邊數 }GraphCrossList; void CreateALGraph(GraphCrossList *G);
.cpp文件
#include "stdafx.h" #include "adjLinkGraph.h" #include <cstdlib> void CreateALGraph(GraphCrossList *G) { int i, j, k; EdgeNode *e; printf("輸入頂點數和邊數:\n"); scanf_s("%d,%d", &G->numVertexes, &G->numEdges); for (i = 0; i < G->numVertexes; i++) { printf("輸入頂點數據:\n"); scanf_s("%d", &G->adjList[i].data); G->adjList[i].firstin = NULL; G->adjList[i].firstout = NULL; } for (k = 0; k < G->numEdges; k++) { printf("輸入邊<vi,vj>上的頂點序號:\n"); scanf_s("%d,%d", &i, &j); /* * firstin 入邊表頭指針,當前頂點作為弧起點 * firstout 出邊表頭指針,當前頂點作為弧終點 * * tailvex 弧起點 * headvex 弧終點 * * taillink 入邊表頭指針,當前結點作為弧起點 * headlink 出邊表頭指針,當前結點作為弧終點 */ e = (EdgeNode *)malloc(sizeof(EdgeNode)); e->tailvex = i; e->headvex = j; e->taillink = G->adjList[i].firstout; e->headlink = G->adjList[j].firstin; G->adjList[i].firstout = e; G->adjList[j].firstin = e; } }
創建並顯示結果
// AdjecentTable.cpp : 定義控制台應用程序的入口點。 // #include "stdafx.h" #include "adjLinkGraph.h" void Display(GraphCrossList G) { int i; EdgeNode *e; printf("共%d個頂點,%d條弧\n",G.numVertexes,G.numEdges); for(i=0;i<G.numVertexes;i++) { printf("頂點%d入度:",G.adjList[i].data); e = G.adjList[i].firstin; while (e) { printf("%d ",G.adjList[e->tailvex].data); e = e->headlink; } printf("出度"); e = G.adjList[i].firstout; while (e) { printf("%d ",G.adjList[e->headvex].data); e = e->taillink; } printf("\n"); } } int main() { GraphCrossList G; CreateALGraph(&G); printf("鄰接表創建成功!"); Display(G); getchar(); return 0; }
結果: