#include <iostream>
using namespace std;
#define Elemtype int
#define maxSize 100
#define initData -1
typedef struct aNode{
    int indexVex;
    struct aNode *nextArcNode;
}arcNode;

typedef struct vNode{
    Elemtype data;
    arcNode *firstArcNode;
}vexNode, adjacencyList[maxSize];

typedef struct {
    adjacencyList vexs;
    int numVexs;
    int numArcs;
}adjacencyListGraph;

void initAdjacenryListGraph(adjacencyListGraph &G) {
    G.numArcs = 0;
    G.numVexs = 0;
    for(int i = 0; i < maxSize; i ++) {
        G.vexs[i].firstArcNode = NULL;
        G.vexs[i].data = initData;
    }
}

int findIndexAdjacenryListGraph(adjacencyListGraph G, Elemtype e) {
    for(int i = 0; i < G.numVexs; i ++) {
        if(G.vexs[i].data == e) return i;
    }
    return -1;
}

Elemtype findVexAdjacenryListGraph(adjacencyListGraph G, int index) {
    if(index >= G.numVexs) return -1;
    else return G.vexs[index].data;
}

void createAdjacenryListGraph(adjacencyListGraph &G) {
    cout << "please cin number of vexs: ";
    int numberVexs;
    cin >> numberVexs;
    G.numVexs = numberVexs;
    cout << "please every vex: ";
    for(int i = 0; i < numberVexs; i ++) {
        cin >> G.vexs[i].data;
    }
    for(int i = 0; i < G.numVexs; i ++) {
        G.vexs[i].firstArcNode = NULL;
    }
    cout << "please cin vexs was linked on edge: ";
    Elemtype firstVex, lastVex;
    int firstIndex, lastIndex;
    cin >> firstVex >> lastVex;
    firstIndex = findIndexAdjacenryListGraph(G, firstVex);
    lastIndex = findIndexAdjacenryListGraph(G, lastVex);
    while(firstIndex != -1 && lastIndex != -1) {
        arcNode *arc1 = new arcNode;
        arc1->nextArcNode = G.vexs[firstIndex].firstArcNode;
        G.vexs[firstIndex].firstArcNode = arc1;
        arc1->indexVex = lastIndex;
        G.numArcs ++;
        arcNode *arc2 = new arcNode;
        arc2->nextArcNode = G.vexs[lastIndex].firstArcNode;
        G.vexs[lastIndex].firstArcNode = arc2;
        arc2->indexVex = firstIndex;
        G.numArcs ++;
        cout << "please cin vexs was linked on edge: ";
        cin >> firstVex >> lastVex;
        firstIndex = findIndexAdjacenryListGraph(G, firstVex);
        lastIndex = findIndexAdjacenryListGraph(G, lastVex);
    }
}

void outputAdjacenryListGraph(adjacencyListGraph G) {
    for(int i = 0; i < G.numVexs; i ++) {
        cout << G.vexs[i].data << ": ";
        arcNode *q = new arcNode;
        q = G.vexs[i].firstArcNode;
        while(q != NULL) {
            int vex = findVexAdjacenryListGraph(G, q->indexVex);
            if(vex != -1) cout << vex << " ";
            q = q->nextArcNode;
        }
        cout << endl;
    }
}

int main() {
    adjacencyListGraph G;
    initAdjacenryListGraph(G);
    createAdjacenryListGraph(G);
    outputAdjacenryListGraph(G);
    return 0;
}
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐