# 图的邻接链表的实现，很容易看懂哦

1 篇文章 0 订阅
1 篇文章 0 订阅
1 篇文章 0 订阅

#include<bits/stdc++.h>
using namespace std;
struct Edge //由于邻接链表表示时链表数组的序数即为起始点，而每个节点可以只带有终点。
{
int endVertex;
int weight;
Edge* next;//下一个与顶点可达的点的指针
Edge(int v,int w):endVertex(v),weight(w),next(NULL){}
};
struct Vertex//顶点索引
{
int neighbor;//相邻节点的个数
};
class Graph
{
private:
Vertex *V;//邻接链表的头节点数组。
int numofvertex;
public:
Graph():V(NULL),numofvertex(0){}
Graph(int num):numofvertex(num)
{
numofvertex=num;
V=new Vertex[num+1];//V[0]不做记录
}
Graph(const Graph & g)//赋值构造函数
{
numofvertex=g.numofvertex;
V=new Vertex[numofvertex];
for(int i=1;i<=numofvertex;i++)
{
V[i].neighbor=g.V[i].neighbor;
{
eg=eg->next;
}
while(eg!=NULL)
{
eg1->next=new Edge(eg->endVertex,eg->weight);
eg1=eg1->next;
eg=eg->next;
}
}
}
~Graph()//析构函数
{
if(V!=NULL)
{
for(int i=1;i<=numofvertex;i++)
{
while(eg!=NULL)
{
eg1=eg;
eg=eg->next;
delete eg1;
}
}
delete [] V;//注意，这个容易被遗忘，不仅仅要删除链表，还有数组本身哦
V=NULL;
}
}
void InsertVertex(int x,int y,int weight)
{
if(x>numofvertex||x<1||y>numofvertex||y<1||x==y)
{
cerr<<"this edge is invalid!!"<<endl;
return ;
}
if(V!=NULL)
{
Edge *eg=new Edge(y,weight);
{
}
else
{
while(eg1->next||eg1->endVertex<y)
{
eg2=eg1;
eg1=eg1->next;
}
eg2->next=eg;
eg->next=eg1;
}
}
V[x].neighbor++;
}
void show()
{
if(V!=NULL)
{
for(int i=1;i<=numofvertex;i++)
{
cout<<i<<"的可达点分别是 ";
while(eg)
{
cout<<eg->endVertex<<" 权值为"<<eg->weight<<" ";
eg=eg->next;
}
cout<<endl;
}
}
}
void DeleteVertex(int x,int y)
{
if(x>numofvertex||x<1||y>numofvertex||y<1||x==y)
{
cerr<<"this edge is invalid!!"<<endl;
return ;
}
if(V)
{
while(eg&&eg->endVertex!=y)//与链表的删除类似哦
{
eg1=eg;
eg=eg->next;
}
if(eg==NULL){cerr<<"no found!!"<<endl;}
else if(eg->endVertex==y)
{
Edge *eg2=eg;
eg1->next=eg->next;
cout<<x<<" "<<y<<"边已被删除"<<endl;
delete eg2;
}
}
V[x].neighbor--;
}
friend void BFS(Graph &g,int m);
friend void DFS(Graph &g,int m);

};
void BFS(Graph &g,int m)
{
queue<int>q;
q.push(m);
int visit[11]={0};
visit[m]=1;
if(!eg){cout<<"none"<<endl;return;}
while(!q.empty())
{
int s=q.front();
q.pop();
cout<<s<<"  ";
if(!eg||!eg->next) continue;
while(eg&&!visit[eg->endVertex])
{
q.push(eg->endVertex);
visit[eg->endVertex]=1;
eg=eg->next;
}
}
}
int visit[11];
void DFS(Graph &g,int m)
{
cout<<m<<"  ";
visit[m]=1;
if(!visit[eg->endVertex])
DFS(g,eg->endVertex);
}
int main(void)
{
Graph g(10);
for(int i=1;i<=10;i++)
{
for(int j=10;j>=1;j--)
{
g.InsertVertex(i,j,rand()%100+1);
}
}
Graph g1(g);
g1.show();
cout<<endl;
g1.DeleteVertex(3,5);
g1.show();
cout<<endl;
int n=2;
BFS(g1,n);
cout<<endl;
DFS(g1,n);
cout<<endl;
return 0;
}


06-29 1641
02-27

12-03 2745
12-08 4200
01-26 444
07-21 1万+
04-24 666
07-08 2万+
05-20 3656
01-28 6599
08-04 2539
11-13 1788
04-27 7681
04-08 4222

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

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

weixin_45525133

¥2 ¥4 ¥6 ¥10 ¥20

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