数据结构——邻接表的创建与打印输出

老样子,三个文件

head.h

#pragma once
#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;

adj.h

#pragma once
#include"head.h"
typedef struct edge
{
	int adjvex;//编号,用于检索data
	int weight;//用于存放权值
	struct edge *next;//邻接表指针
}edgeNode;

typedef struct 
{
	char data;//节点的名字
	edgeNode *first;//用于检索节点邻接表信息,如编号,权值,指向下个孩子的指针
}adj;

class adjListGraph
{
	adj adjList[100];//邻接表表头,最多100个表头
	int v, w;//v为顶点数,w为边数
public:
	void createGraph(void);//录入图信息,存于邻接表
	int locatex(char a);//检索节点名称,返回编号
	void print(void);//打印所有邻接表
};

int adjListGraph::locatex(char a)
{
	for (int i = 0; i < v; i++)
		if (a == adjList[i].data)return i;
	return -1;
}

void adjListGraph::createGraph(void)
{
	int m, n;
	edgeNode *e = NULL;
	edgeNode *q = NULL;
	cout << "依次输入顶点数与边数:" << endl;
	cin >> n >> m;
	v = n;
	w = m;
	cout << "录入邻接表信息:" << endl;
	cout << "录入所有顶点的英文编号:" << endl;
	for(int i = 0; i < n; i++)
	{
		cin >> adjList[i].data;
		adjList[i].first = NULL;
	}
	cout << "录入邻接表信息,以‘起始顶点 被指向顶点 边权值’为格式:" << endl;
	char a, b;
	int cost;
	for (int j = 0; j < w; j++)
	{
		cin >> a >> b >> cost;
		int vertexA = locatex(a);//起始节点的编号
		int vertexB = locatex(b);//被指向节点的编号
		e = new edgeNode;
		e->adjvex = vertexB;
		e->next = NULL;
		//头插法链表
		if (adjList[vertexA].first == NULL)
			q = adjList[vertexA].first = e;
			/*
			单链表标志性的连等写法。根据右结合,等同于
			adjList[vertexA].first=e;
			q=adjList[vertexA].frist;
			*/
		else
			q = q->next = e;
	}
}

void adjListGraph::print(void)
{
	edgeNode *p;
	p = new edgeNode;
	for (int k = 0; k < v; k++)
	{
		cout << adjList[k].data << ":";
		for (p = adjList[k].first; p; p=p->next)
			cout << " " << adjList[p->adjvex].data ;
		if (p == NULL)
			cout << endl;
	}
}

main.cpp

#include"adj.h"
int main(void)
{
	adjListGraph A;
	A.createGraph();
	A.print();
	system("pause");
	return 0;
}

第一组I/O:

输入的拓扑图之这样的:

第二组I/O:

猜你喜欢

转载自blog.csdn.net/qq_41938259/article/details/84999769