簡體   English   中英

如何為遞歸算法實現“取消”按鈕?

[英]How to implement “Cancel” button for a recursive algorithm?

我正在嘗試在文件夾同步應用程序中為算法實現“取消”按鈕。 該算法遞歸地通過用戶指定的目錄結構,將其文件和目錄放入TreeView中,並根據它們是否相對於其他文件夾中的等效項新,刪除,更改或更改來標記它們。 簡化代碼供參考:

fillInTreeView(File x, TreeItem root) {
    if (x.isFile()) {
        newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
        assignMark(newBranch);
    } else {
        newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
        assignMark(newBranch);
        fillInTreeView(x, newBranch);
    }
}

我不知道的是“取消”的含義。 如果我從頂部刪除樹中的所有內容,那么函數是否會繼續添加新內容,從取消算法尚未到達的文件調用自身,使整個按鈕毫無意義? 我想我寧願先問,而不是花幾天時間試圖實施它,只是要稍后再問,重新發現美國。

嘗試它像這樣:

private static boolean cancelled = false;

fillInTreeView(File x, TreeItem root) {
   if(cancelled) return;
   if (x.isFile()) {
        newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
        assignMark(newBranch);
    } else {
        newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
        assignMark(newBranch);
        fillInTreeView(x, newBranch);
    }
}

/*Your CLick-Listener*/
public void onClick(){
       cancelled = true;
}

您應該有一個返回條件,只是導致函數返回該條件。 通過在遞歸調用后檢查此返回,您甚至可以快速崩潰甚至數千次遞歸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM