欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

队列实现(广度优先遍历)

程序员文章站 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;
}

广度优先遍历目录,队列实现。
是目录加入队列不是输出文件(队列是否为空)
没有试过广度和深度遍历文件的效率对比,改日有时间试试
队列实现(广度优先遍历)
队列实现(广度优先遍历)

相关标签: 队列