图的邻接链表存储

//输入样例
/*
 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;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值