开发者

Loop through folders without 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜