#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;
}
|