【数据结构作业 链表 + BFS + DFS】

本文主要介绍了如何使用链表数据结构解决深度优先搜索(DFS)和广度优先搜索(BFS)问题。通过代码实现展示了这两种搜索算法在链表场景中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码:

#include<iostream>
using namespace std;
struct node{
   int a;
   node *next;
};
typedef struct node1{
    char s;
    node *f;
}node1,st[110];
struct node2{
    st ss;
    int vm,vn;
};
struct que{
    int *b;
    int f,r;
};
void Bque(que &Q){
   Q.b = new int[100];
   Q.f = Q.r = 0;
}
void Ique(que &Q,int a){
   if((Q.r + 1) % 100 == Q.f) return ;
   Q.b[Q.r] = a;
   Q.r = (Q.r + 1) % 100;
}
bool Eque(que &Q){
    if(Q.r == Q.f) return true;
    return false;
}
int Dque(que &Q){
    int a = Q.b[Q.f];
    Q.f = (Q.f + 1) % 100;
    return a;
}
int vis[110],viss[110];
int fd(char s,node2 G){
   for(int i = 0; i < G.vm; i++)
    if(G.ss[i].s == s)
       return i;
   return -1;
}
void bulid(node2 &G){
    cout << "输入总的定点数和边数: " << endl;
    cin >> G.vm >> G.vn;
    cout << "依次输入顶点名称(空格隔开):" << endl;
    for(int i = 0; i < G.vm;i++)
        cin >> G.ss[i].s,G.ss[i].f = NULL;
    cout << "依次输入每条边链接的两个点(空格隔开):" << endl;
    for(int i = 0; i < G.vn; i++){
        char s1,s2;
        cin >> s1 >> s2;
        int m1 = fd(s1,G),m2 = fd(s2,G);
        node *p = new node;
        p -> a = m2;
        p -> next = G.ss[m1].f;
        G.ss[m1].f = p;
        node *p1 = new node;
        p1 -> a = m1;
        p1 -> next = G.ss[m2].f;
        G.ss[m2].f = p1;
    }
}
void DFS(node2 G,int a){
    cout << G.ss[a].s << " ";
    node *p = G.ss[a].f;
    while(p){
        if(!vis[p -> a])
            vis[p -> a] = 1,DFS(G,p -> a);
        p = p -> next;
    }
}
void BFS(node2 G,int a){
    que Q;
    cout << G.ss[a].s << " ";
    Bque(Q);
    Ique(Q,a);
    while(!Eque(Q)){
       int o = Dque(Q);
       node *p = G.ss[o].f;
       while(p){
       if(!viss[p -> a]) viss[p -> a] = 1,cout << G.ss[p -> a].s << " ",Ique(Q,p -> a);
       p = p -> next;
     }
    }
}
int main()
{
    node2 G;
    bulid(G);
    cout << "输入合法起点 :" << endl;
    char c; cin >> c;
    int o;
    for(int i = 0; i < G.vm; i++)
        if(G.ss[i].s == c){
            o = i; break;
        }
    cout << "DFS 遍历结果为 :" << endl;
    vis[o] = 1;
    DFS(G,o);
    cout << endl;
    cout << "BFS 遍历结果为 :" << endl;
    viss[o] = 1;
    BFS(G,o);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值