zoukankan      html  css  js  c++  java
  • 采用邻接表表示法创建无向图

    //采用邻接表表示法创建无向图
    #include <iostream>
    using namespace std;
    
    #define MVNnm 100
    #define OK 1
    
    typedef char VerTexType;
    typedef int OtherInfo;
    
    typedef struct ArcNode {
    	int adjvex;
    	struct ArcNode* nextarc;
    	OtherInfo info;
    }ArcNode;
    
    typedef struct VNode {
    	VerTexType data;
    	ArcNode* firstarc;
    }VNode, adjList[MVNnm];
    
    typedef struct {
    	adjList vertices;
    	int vexnum, arcnum;
    }ALGraph;
    
    
    int LocateVex(ALGraph G, VerTexType v) {
    	for (int i = 0;i < G.vexnum;++i) {
    		if (G.vertices[i].data == v) {
    			return i;
    		}
    	}
    	return -1;
    }
    
    int CreatUDG(ALGraph& G) {
    	int i, k;
    	cout << "请输入总顶点数,总边数中间以空格隔开:";
    	cin >> G.vexnum >> G.arcnum;
    	cout << endl;
    
    	for (i = 0;i < G.vexnum;++i) {
    		cout << "请输入第" << (i + 1) << "个点的名称:";
    		cin >> G.vertices[i].data;
    		G.vertices[i].firstarc = NULL;
    	}
    	cout << endl;
    
    	cout << "请输入一条边依附的顶点,如 a b" << endl;
    	for (k = 0;k < G.arcnum;++k) {
    		VerTexType v1, v2;
    		int i, j;
    		cout << "请输入第" << (k + 1) << "条边依附的顶点:";
    		cin >> v1 >> v2;
    		i = LocateVex(G, v1);
    		j = LocateVex(G, v2);
    
    		ArcNode* p1 = new ArcNode;
    		p1->adjvex = j;
    		p1->nextarc = G.vertices[i].firstarc;
    		G.vertices[i].firstarc = p1;
    
    		ArcNode* p2 = new ArcNode;
    		p2->adjvex = j;
    		p2->nextarc = G.vertices[j].firstarc;
    		G.vertices[j].firstarc = p2;
    	}
    	return OK;
    }
    
    int main() {
    	cout << "采用邻接表表示法创建无向图" << endl;
    	ALGraph G;
    	CreatUDG(G);
    	int i;
    
    	cout << endl;
    	cout << "邻接表表示法创建的无向图" << endl;
    
    	for (i = 0;i < G.vexnum;i++) {
    		VNode temp = G.vertices[i];
    		ArcNode* p = temp.firstarc;
    		if (p == NULL) {
    			cout << G.vertices[i].data;
    			cout << endl;
    		}
    		else {
    			cout << temp.data;
    			while (p) {
    				cout << "->";
    				cout << p->adjvex;
    				p = p->nextarc;
    			}
    		}
    		cout << endl;
    	}
    	return 0;
    }
    
    
    
  • 相关阅读:
    ThickBox弹出框的使用方法
    DATASET排序
    jQuery重要插件!
    获取所有querystring变量名
    using要写多少
    【MM系列】SAP MM模块-关于批次特性的查看和获取
    【MM系列】SAP SAP的账期分析和操作
    【ABAP系列】SAP ABAP基础-abap数据类型的解析整理
    【ABAP系列】SAP ABAP基础-录制BDC的MODE定义解析
    【ABAP系列】SAP ABAP基础-数据更新至数据库操作解析
  • 原文地址:https://www.cnblogs.com/ygjzs/p/11877588.html
Copyright © 2011-2022 走看看