链表-例-城市道路和直连城市

CCF,P136, 例6.5

输入城市数、道路数

输入每条道路两端的城市

输出每个城市可直接相连的城市

例:

input:

4 5

2 3

3 1

1 4

2 4

1 2

output:

3 4 2

3 4 1

2 1

1 2

思路:

用链表数组存储每个城市可直连的城市数字(按输入内容录入,一行在两个城市后面分别追加)

代码:

#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
//节点结构体 
struct Node
{
    int v;
    Node *next;
};
//输出链表 
void out_lian(Node *p)
{
    do
    {
        cout<<p->v<<" ";
        p=p->next;
    }
    while(p!=NULL);
}
//追加值(节点)
lian_append(Node *x,Node *y)
{
    Node *head=x;
    //找到链表的结尾节点 
    while(x->next!=NULL)
    {
        x=x->next;
    }
    //追加
    x->next=y; 
}
int main()
{
    int city,road,c1,c2;
    Node *p[10],*t;
    for(int i=0;i<10;i++)
    {
        p[i]=NULL;
    }
    cin>>city>>road;
    for(int j=0;j<road;j++)
    {
        cin>>c1>>c2;
        t=new Node;
        t->v=c2;
        t->next=NULL;
        if(p[c1-1]==NULL)
        {
            p[c1-1]=t;
        }
        else
        {
            lian_append(p[c1-1],t);
        }
        t=new Node;
        t->v=c1;
        t->next=NULL;
        if(p[c2-1]==NULL)
        {
            p[c2-1]=t;
        }
        else
        {
            lian_append(p[c2-1],t);
        }
    }
    for(int i=0;i<city;i++)
    {
        out_lian(p[i]);
        cout<<endl;
    }
}

猜你喜欢

转载自www.cnblogs.com/wanjinliu/p/11410145.html