C++图的邻接表创建

C++图的邻接表存储结构


typedef struct Node{
	int nextVex;
	struct Node *next;
	
} *node;
struct HeadNode{
	E element;
	struct Node *next;
};
typedef struct GraphTable{
	int vex,edge;
	struct HeadNode Vertex[MAXV];
} *Graph;

图的创建函数

Graph create(){
	Graph graph= (Graph)malloc(sizeof(struct GraphTable));
	graph->edge=graph->vex=0;
	return graph;	
}

图的节点添加与边添加函数

void addVex(Graph g,E e){
	g->Vertex[g->vex].element=e;
	g->Vertex[g->vex].next=NULL;
	g->vex++;
}
int getIndexByElem(Graph g,E v){
	int i=0;
	while(true){
	if(g->Vertex[i].element==v)
		return i;	
	i++;
	}
	
}
void addEdge(Graph g,E v1,E v2){
	int a=getIndexByElem(g,v1);
	int b=getIndexByElem(g,v2);
	node nd=g->Vertex[a].next;
	node newNode=(node)malloc(sizeof(struct Node));
	newNode->next=NULL;
	newNode->nextVex=b;
	if(!nd){
		g->Vertex[a].next=newNode;
	}else{
		while(nd->next){
			if(nd->nextVex==b)return;
			nd = nd->next;			
		}
		nd->next=newNode;
	}
	g->edge++;	
}

打印出邻接表

printGraph(Graph g){
	for(int i=0;i<g->vex;++i){
		cout<<i<<" "<<g->Vertex[i].element;
		node nd = g->Vertex[i].next;
		while(nd){
			cout<<"->"<<nd->nextVex;
			nd=nd->next;
		}
		cout<<endl;
	}
}

主函数展示

int main(){
	Graph graph = create();
	for (int c ='A';c<='D';++c)
		addVex(graph,(char)c);
	addEdge(graph,'A','B');
	addEdge(graph,'B','C');
	addEdge(graph,'C','D');
	addEdge(graph,'D','A');
	addEdge(graph,'C','A');
    printGraph(graph);
	return 0;
}
posted @ 2023-12-18 20:26  Happy_Eric  阅读(27)  评论(0编辑  收藏  举报