Menu > Algorithm > その他

適当に並べているだけです。そのうち整理。

目次


再帰関数を使わない再帰処理

再帰的アルゴリズムを実現する方法として、一般に関数呼び出しを再帰させる手法が取られる。
  1. public void recursive(int temp) throws Exception {
  2. System.out.println(temp);
  3.  
  4. if (temp <= 5) {
  5. recursive(temp + 1);
  6. }
  7. }

これをListを使って処理するとこうなる。
  1. LinkedList<Integer> recursive = new LinkedList<Integer>();
  2. recursive.add(0);
  3. while (!recursive.isEmpty()) {
  4. int temp = recursive.remove();
  5. System.out.println(temp);
  6.  
  7. if (temp <= 5) {
  8. recursive.add(temp + 1);
  9. }
  10. }

コンポジットパターンでよく見るツリー検索の場合はちょっとだけ処理を変えて
  1. recursive.addLast(temp + 1);
を使うとディレクトリだけ最初にチェックしたりできる。
最終更新:2013年01月26日 20:49