图的邻接矩阵和邻接表的创建

两个结构体存图:

struct arcnode{
	int data;//存下标i
	arcnode *next;//单链表下个结点
};
struct lianode{
	arcnode *first;//存头结点
};

初始化邻接表

lianode a[55];
void inot(){
	for(int i=0;i<n;i++){
		a[i].first=new arcnode();
		a[i].first->data=i;
		a[i].first->next=NULL;
	}
}

头插法存邻接表

void create(){
	for(int i=0;i<n;i++){
		int x;
		for(int j=0;j<n;j++){
			cin>>x;
			if(x){
				arcnode *p=new arcnode();//开辟一个新的结点空间
				p->next=a[i].first->next;//头插
				p->data=j;//结点的下标是j
				a[i].first->next=p;//接在头结点后面
			}	
		}
	}
}

实例

邻接矩阵转为邻接表

Time Limit: 1000/2000 MS (C/Others)   Memory Limit: 32768/32768 K (C/Others)

Problem Description:
设有向图G,现给出其邻接矩阵,要求将其转化为邻接表(采用头插法存边)进行存储。

Input:
输入数据有多组
每组数据第一行为一个正整数n(0<n<=50),代表G的顶点数目
接下来有n行,为有向图G的邻接矩阵

Output:
对于每组数据,输出有若干行,为该有向图中所有顶点的出边信息(空表不输出任何信息),每行最后均无空格,每两组数据之间有一空行,具体格式见样例。

Sample Input:
3
0 0 1
0 0 0
1 0 0

4
0 1 0 1
1 0 1 0
1 0 0 1
0 0 0 0
Sample Output:
0->2
2->0

0->3->1
1->2->0
2->3->0
Hint:
Source:

代码

#include<iostream>
using namespace std;
struct arcnode{
	int data;
	arcnode *next;
};
struct lianode{
	arcnode *first;
};
int main(){
	int n;
	int c=0;
	while(cin>>n){
		lianode a[55];
		for(int i=0;i<n;i++){
			a[i].first=new arcnode();
			a[i].first->data=i;
			a[i].first->next=NULL;
		}
		for(int i=0;i<n;i++){
			int x;
			for(int j=0;j<n;j++){
				cin>>x;
				if(x){
					arcnode *p=new arcnode();
					p->next=a[i].first->next;
					p->data=j;
					a[i].first->next=p;
				}	
			}
		}
		if(c)
			cout<<endl;
		for(int i=0;i<n;i++){
			if(a[i].first->next){
				cout<<a[i].first->data;
			arcnode *p=a[i].first->next;
			while(p){
				cout<<"->"<<p->data;
				p=p->next;
			}
			cout<<endl;
			}
			
		}
		c++;
	} 
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值