数据结构 — 图之邻接表存储创建和深度优先遍历


【描述】:  该graph采用邻接表存储,首先创建图,然后对其进行深度优先遍历。


【输入】:

8
1 2 -1
0 3 4 -1
0 5 6 -1
1 7 -1
1 7 -1
2 7 -1
2 7 -1
3 4 5 6 -1


【输出】:


0 1 3 7 4 5 2 6 


/*
 * 无向图的邻接表创建
8
1 2 -1
0 3 4 -1
0 5 6 -1
1 7 -1
1 7 -1
2 7 -1
2 7 -1
3 4 5 6 -1
*/

#include<iostream>
#include<memory.h>
using namespace std;

#define MAX_VERTICES 50	/* 顶点最大数 */
#define ElementType int	/* 元素的数据类型 */
bool visited[MAX_VERTICES];	/* 记录顶点是否被访问 */

typedef struct node {	/* 表节点结构体 */
	ElementType vertex;
	struct node *next;
}NodeType,*NodePointer;

NodePointer graph[MAX_VERTICES];	/* 头节点数组 */

int vertices;	/* 顶点数量 */

void CreateGraph(){
	ElementType ch;
	NodePointer pnew,qnode;
	pnew = qnode = NULL;

	for(int i = 0; i < vertices; i++){
		cin>>ch;
		if(ch == -1) continue; /*当ch 为-1是结束该vertex的创建*/
		//链表的头节点
		pnew = new NodeType;
		pnew->vertex = ch;
		pnew->next = NULL;
		//将头节点存入 头节点数组
		graph[i] = pnew;
		//尾插法创建链表
		cin>>ch;
		while(ch != -1){
			//申请内存、处理数据域、处理指针域
			qnode = new NodeType;
			qnode->vertex = ch;
			qnode->next =NULL;
			//插入
			pnew->next = qnode;
			//更新尾指针
			pnew = qnode;
			cin>>ch;
		}
	}
}

void dfs(int v){
	NodePointer np;
	//访问该vertex
	visited[v] = true;
	cout<<v<<" ";
	/*
	 * 图深度优先遍历
	 * 1、访问该节点并且记录
	 * 2、当该节点的next节点没被visited,dfs(next节点)
	 * 3、当该节点的next节点都被visited,结束for,退到上一个visited的节点执行2步骤
	 * 4、都被访问了,函数自然结束
	 */
	for(np = graph[v]; np!=NULL; np = np->next){
		if(!visited[np->vertex])
			dfs(np->vertex);
	}

}

int main(){

	memset(visited,false,sizeof(visited));

	cout<<"输入顶点数"<<endl;
	cin>>vertices;

	CreateGraph();
	cout<<"深度优先遍历"<<endl;
	dfs(0);
	return 0;
}


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PeersLee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值