邻接表-无向图
博客专区 > cyleft 的博客 > 博客详情
邻接表-无向图
cyleft 发表于11个月前
邻接表-无向图
  • 发表于 11个月前
  • 阅读 7
  • 收藏 0
  • 点赞 0
  • 评论 0

【腾讯云】买域名送云解析+SSL证书+建站!>>>   

#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;
}

 

标签: 数据结构 c++ c 学习
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 1
博文 30
码字总数 10068
×
cyleft
两袖轻盈、风姿浪漫
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: