如何创建邻接表(C++实现)

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
//邻接点结点的结构
struct adjNode
{
    int vertice;
    int weight;
    adjNode *next;
};
//顶点的结构
struct verticeNode
{
    int vertice;
    bool flag;
    adjNode *next;
    verticeNode(int a, bool b = false, adjNode *c = nullptr) : vertice(a), flag(b), next(c){}
};
//构建函数
vector<verticeNode> BuildAdjList(int arr[],int length);
vector<verticeNode> BuildAdjList(int arr[],int length)
{
    int n, weight;
    vector<verticeNode> AdjList;
    for (int i = 0; i < length; i++)
    {
        verticeNode tmp(arr[i]);
        adjNode *adjPoint = (adjNode *)malloc(sizeof(adjNode));
        tmp.next = adjPoint;
        cout << "please input the all pairs of the adjacent point and weight: ";
        for (;;)
        {
            if (cin >> n >> weight)
            {
                adjPoint->vertice = n;
                adjPoint->weight = weight;
                adjPoint->next = (adjNode *)malloc(sizeof(adjNode));
                adjPoint = adjPoint->next;
            }
            else
            {
                cin.clear();
                cin.ignore();
                break;
            }
        }
        AdjList.push_back(tmp);
    }
    return AdjList;
}

以下是测试用例

int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    vector<verticeNode> adjList = BuildAdjList(arr,5);
    cout << adjList[3].next->weight << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值