算法第四版1.3背包、队列和栈:习题1.3.43

import java.io.File;
import java.util.Iterator;
import edu.princeton.cs.algs4.StdOut;

public class ListFile implements Iterable{
    public static void main(String[]args){
        ListFile lf=new ListFile("C:\\Users\\0\\Desktop\\testfolder");//test path
        for (Object s:lf)
            StdOut.println(s);
    }

    private FileNode first;
    private FileNode last;
    private int N;
    private class FileNode{
        String item;
        FileNode next;
    }
    public ListFile(String Path){
        ConstructList(Path);
    }
    private void ConstructList(String Path){
        File file=new File(Path);
        if (!file.isDirectory()){//is File
            FileNode newlast=new FileNode();
            newlast.item=file.getName();
            if (first==null){
                first=newlast;
                last=newlast;
            }
            else {
                last.next=newlast;
                last=newlast;
            }
            N++;
        }
        else {//is Folder
            File[] files=file.listFiles();
            for (File file1:files)
                ConstructList(file1.getPath());
        }
    }
    public Iterator iterator(){
        return  new ListFileIterator();
    }
    private class ListFileIterator implements Iterator{
        private  FileNode current=first;
        public boolean hasNext() {
            return current!=null;
        }
        public String next(){
            String item=current.item;
            current=current.next;
            return item;
        }
    }
}

testfolder文件夹如图

算法第四版1.3背包、队列和栈:习题1.3.43_第1张图片

folder1文件夹如图

算法第四版1.3背包、队列和栈:习题1.3.43_第2张图片

folder文件夹如图

算法第四版1.3背包、队列和栈:习题1.3.43_第3张图片

测试结果 如下:

算法第四版1.3背包、队列和栈:习题1.3.43_第4张图片

你可能感兴趣的:(算法第四版1.3背包,队列和栈课后习题)