0
点赞
收藏
分享

微信扫一扫

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

王小沫 2022-03-18 阅读 24
#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;
}
举报

相关推荐

0 条评论