数据结构——STL实现邻接表输入与打印

按照之前没用STL的那个改了一下,直接给出代码:

#include<iostream>
#include<vector>
#define maxn 1000
using namespace std;

struct node
{
	int adjvex;
	char data;
	int weight;
};

vector<node> adj[maxn];
bool visited[maxn] = { false };
int n;

void createNode(char a,int i,int w=0)
{
	node temp;
	temp.adjvex = a-'a';
	temp.data = a;
	temp.weight = w;
	adj[i].push_back(temp);
}

void create()
{
	int m;
	cin >> n >> m;
	for (int i = 0; i < n; i++)
	{
		char tempA;
		cin >> tempA;
		createNode(tempA, i);
	}
	char a, b;
	int cost,aa,bb;
	for (int i = 0; i < m; i++)
	{
		cin >> a >> b >> cost;
		for (int j = 0; j < n; j++)
		{
			if (a == adj[j][0].data)
				aa = adj[j][0].adjvex;
		}
		createNode(b, aa, cost);
	}
}

void print()
{
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < adj[i].size(); j++)
		{
			cout << adj[i][j].data <<adj[i][j].weight << ' ';
		}
		cout << endl;
	}
}

int main(void)
{
	create();
	print();
	system("pause");
	return 0;
}

接着是测试图:

posted @   TIM3347_Tian  阅读(18)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示