邻接表的几种存储方式

来源:互联网 发布:mac svn客户端下载 编辑:程序博客网 时间:2024/05/06 19:57

总的来说有以下三种方式:

链表:

//存储结构 struct Node{    int vex;    Node* next;}; Node *head[M]; //添加一个有向边 void addADJ(int u,int v){    Node *p;    p=(Node*)malloc(sizeof(Node));    p->vex=v;    p->next=head[u];    head[u]=p;}//遍历for(Node *p=head[u];p!=NULL;p=p->next)    int v=p->vex;//连接u的结点v//初始化memset(head,NULL,sizeof(head));
链式前向星:(有点儿静态链表意思)

//存储结构struct Edge{    int next;    int to;}edge[M];int head[M];int cnt=0; //添加一个有向边void add(int u,int v){    edge[cnt].to=v;    edge[cnt].next=head[u];    head[u]=cnt++;}//遍历for(int i=head[u];~i;i=edge[i].next)    int v=edge[i].to;    //初始化memset(head,-1,sizeof(head));
stl库:

//存储结构vector<int> node[M];//添加一个有向边node[u].push_back(v);//遍历for(int i=0;i<node[u].size();i++)    int v=node[u][i];