数据结构->有向图邻接表的创建(纯小白向)

该代码示例展示了如何在C++中使用邻接表数据结构创建和遍历有向图。程序首先定义了ArcNode和Vnode结构体,然后创建了一个AGraph结构体来存储图的信息。在`create()`函数中,用户输入顶点和边的数量,接着程序构建邻接表。最后,`travseTree()`函数遍历邻接表打印出每个顶点相邻的顶点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有向图的邻接表创建和无向图的邻接表创建类似,甚至步骤更加简单

#include<iostream>
#define maxSize 30        
using namespace std;
typedef struct ArcNode {
    int adjvex;
    struct ArcNode *nextarc;
} ArcNode;
  
typedef struct {
    int data;
    ArcNode *firstarc;
} Vnode;
  
//可以利用结构体整体结构,也可以拆分结构体变为单独搜索
typedef struct {
    Vnode adjlist[maxSize];
    int n, e;//n数目 e边数 
} AGraph;
  
AGraph *graph;
  
void create() {
    graph = new AGraph; 
    cout << "输入顶点的数目: " << endl;
    cin >> graph->n;
    cout << "输入图中边的数目: " << endl;
    cin >> graph->e;
  
    int u = -1, v = -1;
    
    for(int i = 0; i < graph->n ; i++) {
        graph->adjlist[i].data = i; 
        graph->adjlist[i].firstarc = NULL;
    }
  
    ArcNode *node;
    
    for(int i = 0 ; i < graph->e ; i++){
        cout<<"输入一条边上两个点的数字信息(u,v)(u表示头节点,v表示尾节点)"<<endl;
        cin>>u>>v;
        node = new ArcNode;
        node->adjvex = v;
        node->nextarc = nullptr;
        if(graph->adjlist[u].firstarc==nullptr){
            graph->adjlist[u].firstarc = node; 
        } 
        else{
            //头插法 
            node->nextarc = graph->adjlist[u].firstarc->nextarc;
            graph->adjlist[u].firstarc->nextarc = node;
        }
    }
    
}
  
void  travseTree() {
    for(int i = 0; i < graph->n; i++) {
        if(graph->adjlist[i].firstarc != NULL) {
            cout <<"与"<< i << "连接的点有:"<<"  ";
            ArcNode *p = graph->adjlist[i].firstarc;
            while(p != NULL) {
                cout << p->adjvex << " -> ";
                p = p->nextarc;
            }
            cout << endl;
        }
    }
}
  
int main(void) {
    create();
    travseTree();
    return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值