队列实现(广度优先遍历)
程序员文章站
2022-03-08 19:00:52
...
#include <iostream>
#include <string.h>
#include <queue>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
void *widfirsearch(const char* pathname)
{
printf("传入目录:%s\n",pathname);
queue<string> q;
DIR *dir = NULL;
struct dirent * pdir = NULL;
q.push(pathname);
//if queue not empty
while(0 != q.size())
{
const char *path = q.front().c_str();
dir = opendir(path);
if(nullptr == dir)
{
printf("open dir failed2\n");
return nullptr;
}
while(NULL != (pdir = readdir(dir)))
{
if(pdir->d_type == DT_DIR)
{
if(0 == strcmp(pdir->d_name,".") || 0 == strcmp(pdir->d_name,".."))
continue;
string TmpPath(path);
TmpPath += "/";
TmpPath += pdir->d_name;
q.push(TmpPath);
printf("目录1:%s入队\n",TmpPath.c_str());
}
else
{
printf("The filename:%s\n",pdir->d_name);
}
}
q.pop();
closedir(dir);
}
return NULL;
}
int main()
{
widfirsearch("/home/itheima/work");
return 0;
}
广度优先遍历目录,队列实现。
是目录加入队列不是输出文件(队列是否为空)
没有试过广度和深度遍历文件的效率对比,改日有时间试试
上一篇: 九种 分布式ID生成方式