#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++实现图的邻接表
最新推荐文章于 2024-05-05 03:22:11 发布