图的基本操作——邻接链表表示(网(边带权值的图)的编程没有给出,与一般的图类似)

#define VertexType int//顶点的类型
#define MAX_VERTEX_NUM 20 //最大顶点数
#define Status int
#define OK 1
#define ERROR 0
#define NULL 0

	typedef enum{NG, DG, NW, DW}GraphType;//图的类型

typedef struct ArcNode{	 //边结点
	int adjvex;	//邻接点的下标
	struct ArcNode	*nextarc; //后继链指针
}ArcNode;

typedef struct VNode{	 //顶点结点
	VertexType data;	 //顶点数据 
	ArcNode *firstarc;	//边链头指针
}VNode, AdjList[MAX_VERTEX_NUM];

typedef struct{
	AdjList vertices;	 //邻接表
	int vexnum,arcnum;	//顶点数和边数
	GraphType kind;	 //图种类标志
}AlGraph;


 

 

#include<iostream>
#include"temp1.h"
#include<fstream>
	using namespace std;

Status CreateAlGraph(AlGraph &G){
	ifstream in;
	in.open("data3.txt", ios::in);
	cout<<"下列数据从文件data3.txt读入"<<endl<<endl;
	cout<<"请输入图的顶点数,边/弧的数目,图的类型"<<endl;
	int kind;
	in>>G.vexnum>>G.arcnum>>kind;//从文件读入数据,遇到任何结束标记(如空格和换行)则停止。
	switch(kind){
	case 0 :
		G.kind = NG;
		break;
	case 1:
		G.kind = DG;
		break;
	case 2:
		G.kind = NW;
		break;
	case 3:
		G.kind = DW;
		break;
	}
	cout<<"请依次输入顶点的值"<<endl;
	for(int i = 0; i < G.vexnum; i++){
		in>>G.vertices[i].data;
		G.vertices[i].firstarc = NULL;
	}
	cout<<"请依次输入一条边的起点和终点:"<<endl;
	for(int k = 0; k < G.arcnum; k++){
		int i, j;
		in>>i>>j;
		ArcNode *p = new ArcNode;
		p->adjvex = j;
		//头插入
		p->nextarc = G.vertices[i].firstarc;
		G.vertices[i].firstarc = p;
		if(G.kind == NG){
			ArcNode *p = new ArcNode;
			p->adjvex = i;
			//头插入
			p->nextarc = G.vertices[j].firstarc;
			G.vertices[j].firstarc = p;
		}
	}
	in.close();
	return OK;
}

int Degree(AlGraph G, VertexType v){
	int i;
	for(i = 0; i < G.vexnum; i++){
		if(G.vertices[i].data == v){
			break;
		}
	}
	if(i >= G.vexnum){
		return -1;
	}
	ArcNode *p = G.vertices[i].firstarc;
	int num = 0;
	while(p){
		num++;
		p = p->nextarc;
	}
	if(G.kind == DG){
		for(int k = 0; k < G.vexnum; k++){
			if(k == i){
				continue;
			}
			p = G.vertices[k].firstarc;
			while(p){
				if(p->adjvex == i){
					num++;
				}
				p = p->nextarc;
			}
		}
	}
	return num;
}

Status InsertVex(AlGraph &G, VertexType v){
	//先判断v是否存在
	for(int i = 0; i < G.vexnum; i++){
		if(G.vertices[i].data == v){
			return ERROR;
		}
	}
	G.vertices[G.vexnum].data = v;
	G.vertices[G.vexnum].firstarc = NULL;
	G.vexnum++;
	return OK;
}

int main(){
	//依次测试函数CreateMGraph Degree IsAdj InsertVertex 
	//InsertAdj DeleteAdj
	AlGraph G;
	CreateAlGraph(G);
	int n;
	n = Degree(G, 2);
	cout<<"顶点2的度为:"<<n<<endl;
	InsertVex(G, 5);
	system("pause");
	return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值