我们在我的 Java 类介绍中学习递归,我很难理解给出的示例中的方法是如何工作的。调用该方法时会发生什么?
这是代码:
public class Hanoi
private int n;
private int pegA;
private int pegB;
public Hanoi(int in_n, int in_pegA, int in_pegB)
{
n = in_n;
pegA = in_pegA;
pegB = in_pegB;
}
public void makemoves()
{
if (n==1)
System.out.format("%d ==> %d%n", pegA, pegB)
else
{
int otherPeg = 6 - pegA - pegB; // 1 + 2 + 3 =6
Hanoi firstmove = new Hanoi (n-1, pegA, otherPeg);
firstmove.makemoves();
System.out.format("%d ==> %d%n", pegA, pegB);
Hanoi secondmove = new Hanoi (n-1, otherPeg, pegB);
secondmove.makemoves();
}
}
}