简体   繁体   中英

How do I print adjacent list in specific format without using the C++ standard library?

I have an undirected weighted graph:

图形

I want to print an adjacent list in the following format:

0--> 1 --> 2
1 --> 0 --> 2 --> 3
2 --> 0 --> 1 --> 4
3 --> 1 --> 4
4 --> 2 --> 3 --> 5
5 --> 4 --> 6
6-->5

This is my code:

#include <iostream>
using namespace std;

int main()
{
    int nodes = 7;
    int graphList[nodes][nodes];

    for(int i = 0; i<nodes;i++){
        for(int j = 0; j<nodes;j++){
            graphList[i][j]=0;
        }
    }

    int n1, n2, weight;

    for(int j = 0; j<8;j++){
        cin>>n1>>n2>>weight;
        graphList[n1][n2]= weight;
        graphList[n2][n1]= weight;
    }

    cout<<"Adjacent list: \n";
    for(int i = 0; i<nodes;i++){
        for(int j = 0; j<nodes;j++){
            if(graphList[i][j]!=0){
                cout<<i<<"-->"<<j<<endl;
            }
        }
    }

    return 0;
}

This way I was able to get output like this:

 Adjacent list:
    0-->1
    0-->2
    1-->0
    1-->2
    1-->3
    2-->0
    2-->1
    2-->4
    3-->1
    3-->4
    4-->2
    4-->3
    4-->5
    5-->4
    5-->6
    6-->5

How can I print like the mentioned format, without using the C++ standard library?

Note: It is an assignment, and so I cannot use the standard library as a requirement.

Since you are able to output the adjacency list alphabetically by the first element, you can simply output the format as you desire with a flag within the inner loop of:

    cout<<"Adjacent list: \n";
    for(int i = 0; i<nodes;i++){
        bool flag = true;
        for(int j = 0; j<nodes;j++){
            if(graphList[i][j]!=0){
                if (flag) {
                    cout<<i<<"-->"<<j;
                    flag = false;
                }
                else {
                    cout<<"-->"<<j;
                }
            }
        }
        cout<<endl;
    }

In the if statement, if first inside it, then output the first element otherweise, output "-->" second element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM