线性结构存储图的代码实验

测试代码

#include<algorithm>
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

class stu
{
    public:
    int u,next,value;
    stu(){};
    stu(int a,int b,int c):u(a),next(b),value(c){};
};

stu mapper[100];
int cnt;
int head[1000];

void add(int u,int v,int w)
{
    mapper[cnt] = stu(v,head[u],w);
    head[u] = cnt++;
}

int init()
{
    memset(head,-1,sizeof(head));
    cnt = 0;
    return 0;
}

//

int print(int u)
{
    cout<<"=========================="<<endl;
    cout<<"vertex "<<u<<" has:"<<endl;
    for(int i=head[u];~i;i=mapper[i].next)
    {
        cout<<mapper[i].u<<" "<<mapper[i].value<<endl;
    }
    cout<<"OVER"<<endl;
    return 0;
}

int readin()
{
    int u,v,value;
    while(cin>>u>>v>>value) add(u,v,value);
    return 0;
}

int main()
{
    freopen("in.txt","r",stdin);
    init();
    readin();
    for(int i=0;i<8;i++)
    {
        print(i);
    }
    return 0;
}

输入文件

3 5 5
3 6 7
2 6 7
2 7 3
0 2 6
1 3 6
4 6 23
6 2 79
7 2 6
5 7 2

运行结果

==========================
vertex 0 has:
2 6
OVER
==========================
vertex 1 has:
3 6
OVER
==========================
vertex 2 has:
7 3
6 7
OVER
==========================
vertex 3 has:
6 7
5 5
OVER
==========================
vertex 4 has:
6 23
OVER
==========================
vertex 5 has:
7 2
OVER
==========================
vertex 6 has:
2 79
OVER
==========================
vertex 7 has:
2 6
OVER

所以核心代码是:

class stu
{
    public:
    int u,next,value;
    stu(){};
    stu(int a,int b,int c):u(a),next(b),value(c){};
};

stu mapper[100];
int cnt;
int head[1000];

void add(int u,int v,int w)
{
    mapper[cnt] = stu(v,head[u],w);
    head[u] = cnt++;
}

int init()
{
    memset(head,-1,sizeof(head));
    cnt = 0;
    return 0;
}

OK

posted @ 2020-08-31 17:15  SavenNeer  阅读(159)  评论(0编辑  收藏  举报