2011-04-09 62 views

回答

2

這裏是一個可能的實現:

import java.util.ArrayList; 

public class LinearAckermann { 

    static ArrayList<Long> mList = new ArrayList<Long>(); 

    public static long ackermann(long m, long n) { 
     while (true) { 
      if (m == 0) { 
       n += 1; 
       if (mList.isEmpty()) { 
        return n; 
       } else { 
        int index = mList.size() - 1; 
        m = mList.get(index); 
        mList.remove(index); 
       } 
      } else if (n == 0) { 
       m -= 1; 
       n = 1; 
      } else { 
       mList.add(m - 1); 
       n -= 1; 
      } 
     } 
    } 

    public static void main(String[] args) { 
     System.out.println(ackermann(4, 1)); 
    } 
} 

它採用mList,而不是一個堆棧持有待審批工作;當堆棧變空時,它可以返回累計值。

+0

_this_應該做什麼,它如何增加接受的答案? – greybeard 2015-06-25 06:26:07

+1

這是Ackermann函數的非遞歸實現,檢查結果並看到它確實給出了相同的結果。除了這個答案我不明白你會期望什麼。 – ungalcrys 2015-06-25 09:38:10

+0

令人驚訝的是,我們想出了幾乎完全相同的代碼 - 只有兩種不同的語言。 – 2016-01-15 15:13:29