【发布时间】:2012-11-08 20:28:48
【问题描述】:
我们在我的 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();
}
}
}
【问题讨论】:
-
你面临什么问题明白吗?您是否尝试追踪该代码?
-
你必须问一个具体的问题
-
追踪代码是什么意思?我无法逐行理解会发生什么。那么当 firstmove.makemoves 被调用时,它会立即通过创建一个 Hanoi firstmove 的新实例来重新开始吗?还是继续到 System.out.format,然后是 Hanoi secondmove,然后是 secondmove.makemoves(),然后重新开始?
-
尝试理解递归(我假设这是你关心的问题)ocw.mit.edu/courses/electrical-engineering-and-computer-science/…
-
@JamesChristopher。是的。这就是发生的事情。使用递归理解代码的最佳方法是使用
Stack。不是在代码中,而是在纸上。