问题
I have 3 class, Root, CFile, SubDirectory. Root is a abstract class. CFile and SubDirectory are derived from Root. CFile has attributes: name:string , size:int, level:int. SubDirectory has attributes: name:string, size:int, level:int,a vector, which contains both files and directories and a function void add() to push the file or directory into the vector. If a file in a directory, file's level is higher than the directory's by one. All setters and getters are defined.
Now, I have a file called DirRead.h that can struct all the entries in the current diretory (computer's folder). Each entry has a filename, size, level and type (either File or Directory). In the main function, I'm asked to use the information from DirRead as input to construct the hierarchy of file system (using CFile and SubDirectory). DirRead.h conducts pre-order triversal. Recursion is not accepted in this case (I tried, and DirRead.h reported error). I'm asked to use stack to deal with the input, but I don't know how. Apparently level is really important here. I have tried to create a stack and push all the files and directories into the stack, then compare the level to form the hierarchy. But Root doesn't have Add function, there's no way to add CFile into SubDirectory because they are all Root*. Anyone knows how to do this? Thx.
回答1:
You use the stack to keep track of directories you haven't explored yet. You can use the following algorithm:
Push the root directory onto the stack.
Pop the top entry off the stack. If the stack is empty, stop, you're done.
Traverse the directory you pulled off the stack. Add every file and directory in it into your data structure. Also, push every directory you find onto your stack.
Go to step 2.
来源:https://stackoverflow.com/questions/14867821/chow-to-use-stdstack-to-deal-with-the-file-directory-hierarchy