码迷,mamicode.com
首页 > 其他好文 > 详细

图的邻接链表存储

时间:2016-05-07 07:40:47      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

//输入样例
/*
 5 0
 AB AD AC CD BE DE  
 */
//输出
/*
 Please Input the edge x-->y:AB AD AC CD BE DE
 A  1  2  3
 B  0  4
 C  0  3
 D  0  2  4
 E  1  3
 */
#include<iostream>
#include<cstdio>
using namespace std;
#define MAXVER 10
typedef char Elemtype;
//接下来要连的结点
typedef struct node{
    int num;
    struct node *next;
}slink;
//首结点数组
typedef struct{
    struct{
        Elemtype vertex;
        slink *first;
    }ve[MAXVER];
    int vex,edge,tag;
}adjlist;
//使用简单结构建立图的邻接表
void cregraph(adjlist *G,int n,int m)
{
    G->vex=n;
    G->tag=m;
    int e=0;
    slink *s,*p,*q;
    for(int i=0;i<n;i++){
        G->ve[i].vertex='A'+i;
        G->ve[i].first=NULL;
    }
    Elemtype x,y;
    printf("Please Input the edge x-->y:");
    scanf("%c%c",&x,&y);
    while(x!=' '&&y!=' ')
    {
        e++;
        s=(slink *)malloc(sizeof(slink));
        s->num=y-'A';
        if(G->ve[x-'A'].first==NULL){
            G->ve[x-'A'].first=s;
            s->next=NULL;
        }
        else{
            p=G->ve[x-'A'].first;
            if(p->num>s->num){
                s->next=p;
                G->ve[x-'A'].first=s;
            }
            else{
                q=p->next;
                while(q!=NULL&&q->num<s->num)
                {
                    p=q;
                    q=q->next;
                }
                p->next=s;
                s->next=q;
            }
        }
        if(!G->tag)
        {
            s=(slink *)malloc(sizeof(slink));
            s->num=x-'A';
            if(G->ve[y-'A'].first==NULL) {G->ve[y-'A'].first=s;s->next=NULL;}
            else{
                p=G->ve[y-'A'].first;
                if(p->num>s->num)
                {s->next=p;G->ve[y-'A'].first=s;}
                else{
                    q=p->next;
                    while(q!=NULL&&q->num<s->num) {p=q;q=q->next;}
                    p->next=s;
                    s->next=q;
                }
            }
        }
        getchar();
        scanf("%c%c",&x,&y);
    }
    G->edge=e;
}
//输出用邻接表表示的图的算法
void list(adjlist *G)
{
    slink *p;
    for(int i=0;i<G->vex;i++)
    {
        p=G->ve[i].first;
        printf("%c",G->ve[i].vertex);
        while(p)
        {
            printf("%3d",p->num);
            p=p->next;
        }
        printf("\n");
    }
}
int main()
{
    adjlist *G;
    G=(adjlist *)malloc(sizeof(adjlist));
    int n,m;
    scanf("%d%d",&n,&m);
    getchar();
    cregraph(G,n,m);
    list(G);
    return 0;
}

图的邻接链表存储

标签:

原文地址:http://blog.csdn.net/qq_33901573/article/details/51332841

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!