C++实现图的邻接表
2015-09-11 21:17
495 查看
#include<iostream> #include "malloc.h" using namespace std; #define Max 100 //邻接表实现图的DFS //邻接表每一个链表节点的结构,有一个指向下一个节点的指针,一个存放权值的结构,一个存放节点的信息 typedef struct node { int data; struct node* next; int info; }linknode; //表头信息,每一个节点都可以成为一次表头 typedef struct nodeheader { int data; linknode* first; }nodeh; typedef struct graph { int n,e; nodeh adjaceTable[Max]; }Graph; void initGraph(Graph* &g) { cin>>g->n>>g->e; for(int i=0;i<g->n;i++) { cin>>g->adjaceTable[i].data; g->adjaceTable[i].first = NULL; } for(int j=1;j<=g->e;j++) { cout<<"in"<<endl; int node1,node2; cin>>node1>>node2; cout<<node1<<node2; for(int k=0;k<g->n;k++) { cout<<"ins"<<endl; if(g->adjaceTable[k].data == node1) { if(g->adjaceTable[k].first == NULL) { linknode *nodes = (linknode*)malloc(sizeof(linknode*)); nodes->data = node2; nodes->next = NULL; g->adjaceTable[k].first = nodes; } else { linknode *p = g->adjaceTable[k].first; while(p->next != NULL) p= p->next; linknode *nodes = (linknode*)malloc(sizeof(linknode*)); nodes->data = node2; nodes->next = NULL; p->next = nodes; } } if(g->adjaceTable[k].data == node2) { if(g->adjaceTable[k].first == NULL) { linknode *nodes = (linknode*)malloc(sizeof(linknode*)); nodes->data = node1; nodes->next = NULL; g->adjaceTable[k].first = nodes; } else { linknode *p = g->adjaceTable[k].first; while(p->next != NULL) p= p->next; linknode *nodes = (linknode*)malloc(sizeof(linknode*)); nodes->data = node1; nodes->next = NULL; p->next = nodes; } } } } } void printGraph(Graph* g) { for(int i=0;i<g->n;i++) { cout<<g->adjaceTable[i].data; if(g->adjaceTable[i].first != NULL) { linknode *p = g->adjaceTable[i].first; cout<<p->data<<""; p = p->next; while(p != NULL) { cout<<p->data<<""; p= p->next; } } cout<<endl; } } int main() { Graph *g = (Graph*)malloc(sizeof(Graph*)); initGraph(g); printGraph(g); return 0; }
相关文章推荐
- C++中智能指针的设计和使用
- 设计模式(c++版)
- C/C++
- C语言学习之结构体struct
- Effective C++ 条款45 运用成员函数模板接受所有兼容类型
- 为什么在C++使用pthread_create()的时候,类成员函数做线程的处理函数必须要定义成static类型的?
- C语言实现的百分比加进度条的显示程序
- C++_递归习题汇总
- C语言指针和文件笔记
- C++面试考点
- C++面试考点
- 【more effective c++读书笔记】【第6章】杂项讨论
- 【more effective c++读书笔记】【第6章】杂项讨论
- 详解C++编程中用数组名作函数参数的方法
- C语言中int到float的强制类型转换
- C++ STL 常用方法(函数)之-map篇
- C++、C中有关double、float类型转换成int型,及取整,丢失精度问题。
- c语言 函数返回二位数组 函数参数为二维数组
- 猴子分桃
- P2P通信原理与实现(C++)