邻接表-无向图

#include <iostream>

using namespace std;
#define MVNum 10
typedef char OtherInfo;
typedef char VerTexype;
typedef int Status;

string str[10] = {"th","st","nd","th","th","th","th","th","th","th"};

typedef struct ArcNode{
    int adjvex;
    struct ArcNode * nextarc;
    OtherInfo info;
}ArcNode;

typedef struct VNode{
    VerTexype data;
    ArcNode *firststarc;
}VNode,AdjList[MVNum];

typedef struct {
    AdjList vertices;
    int vexnum,arcnum;
}ALGraph;

int LocateVex(ALGraph G,VerTexype v);

void init(ALGraph &G,int vexnum,int arcnum){
    G.arcnum = arcnum;
    G.vexnum = vexnum;
    for(int i=0;i<vexnum;i++){
        G.vertices[i].firststarc = NULL;
    }
}

Status CreateUDG(ALGraph &G){
    VerTexype v1,v2;
    cout<<"Please enter vexnum and arcnum:"<<endl;
    cin>>G.vexnum>>G.arcnum;
    cout<<"The vexnum and arcnum are "<<G.vexnum<<" and "<<G.arcnum<<" respectively"<<endl<<endl;
    init(G,G.vexnum,G.arcnum);
    for(int i=0;i<G.vexnum;i++){
        cout<<"Please enter the "<<i<<str[i]<<" vex is:"<<endl;
        cin>>G.vertices[i].data;
    }
    cout<<endl;
    for(int i=0;i<G.arcnum;i++){
        cout<<"Please enter the starting point and end point"<<endl;
        cin>>v1>>v2;

        int x = LocateVex(G,v1);
        int y = LocateVex(G,v2);
        while(x==-1||y==-1||x==y){
            cout<<"Maybe you typed the wrong one,please enter again"<<endl;
            cout<<"Please enter the starting point and end point"<<endl;
            cin>>v1>>v2;

            x = LocateVex(G,v1);
            y = LocateVex(G,v2);
        }
        cout<<"--------------------"<<endl;
        ArcNode *p1 = new ArcNode;
        p1->adjvex = y;
        p1->nextarc = G.vertices[x].firststarc;
        G.vertices[x].firststarc = p1;

        ArcNode *p2 = new ArcNode;
        p2->adjvex = x;
        p2->nextarc = G.vertices[y].firststarc;
        G.vertices[y].firststarc = p2;
    }
    return 1;
}

void ALGraphDisplay(ALGraph G){
    for(int i=0;i<G.vexnum;i++){
        cout<<G.vertices[i].data<<" ";
        while(G.vertices[i].firststarc!=NULL){
            cout<<G.vertices[i].firststarc->adjvex<<" ";

            G.vertices[i].firststarc = G.vertices[i].firststarc->nextarc;
        }
        cout<<endl;
    }
}

int main()
{
    ALGraph alg;
    CreateUDG(alg);
    ALGraphDisplay(alg);
    return 0;
}

int LocateVex(ALGraph G,VerTexype v){
    for(int i=0;i<G.vexnum;i++){
        if(G.vertices[i].data==v){
            return i;
        }
    }
    return -1;
}

 

转载于:https://my.oschina.net/lafter/blog/901748

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值