万金流
以码会友。 吾Q:578751655。 水平有限,轻喷,谢!
随笔 - 189,  文章 - 0,  评论 - 7,  阅读 - 14万

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;
    }
}
复制代码

 

posted on   万金流  阅读(259)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现

点击右上角即可分享
微信分享提示