开发者

Loop through folders without recursion

开发者 https://www.devze.com 2023-02-14 18:13 出处:网络
I was looking for an algorithm, so OS is not problem, in how to loop through folders without the use of recursion.

I was looking for an algorithm, so OS is not problem, in how to loop through folders without the use of recursion.

Recursion is not the answer because recursion cannot go to "infini开发者_JAVA百科ty" and beyond, while a "while loop" can get there.

Programming language doesn't matter.


You can use a stack data structure for depth-first traversal. Here is some sample code in C#:

    var stack = new Stack<string>();

    stack.Push(@"C:\");

    while (stack.Count > 0)
    {
        var currentDirectory = stack.Pop();
        Console.WriteLine("Visiting: " + currentDirectory);

        foreach (var childDirectory in Directory.GetDirectories(currentDirectory))
        {
            stack.Push(childDirectory);
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号