難以找出如何將此遞歸方法更改爲迭代方法,任何人都有任何有用的指針?我得到了遞歸方法的工作方式,但不太清楚轉換爲迭代的步驟,謝謝。在你的代碼將遞歸循環更改爲迭代
private static void printFriends(Friend friend, int distance) {
if (distance == 0) {
System.out.println(friend);
} else {
for (Friend f : friend.getFriends()) {
System.out.println(f + "0");
printFriends(f, distance - 1);
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
List<Friend> friendList = new ArrayList<Friend>();
Friend reuben = new Friend("Reuben");
Friend soumitra = new Friend("Soumitra");
Friend ken = new Friend("Ken");
Friend elisa = new Friend("Elisa");
Friend isaac = new Friend("Isaac");
friendList.add(reuben);
friendList.add(soumitra);
friendList.add(ken);
friendList.add(elisa);
friendList.add(isaac);
reuben.addFriend(soumitra);
reuben.addFriend(ken);
soumitra.addFriend(reuben);
ken.addFriend(reuben);
ken.addFriend(elisa);
elisa.addFriend(ken);
elisa.addFriend(isaac);
isaac.addFriend(elisa);
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
String inputName = "";
String inputValue = "";
Friend inputFriend = null;
int inputInt = 0;
System.out.println("Blank entry at any prompt exits program.");
while (true) {
System.out.print("Enter a person's name: ");
try {
inputName = inputReader.readLine();
} catch (IOException e) {
System.err.println("Error reading from console.");
}
if (inputName.equals("")) {
System.out.println("Run complete.");
System.exit(0);
}
inputFriend = new Friend(inputName);
if (friendList.contains(inputFriend)) {
inputFriend = friendList.get(friendList.indexOf(inputFriend));
System.out.print("Enter a non-negative integer: ");
try {
inputValue = inputReader.readLine();
} catch (IOException e) {
System.err.println("Error reading from console.");
}
if (inputValue.equals("")) {
System.out.println("Run complete.");
System.exit(0);
}
try {
inputInt = Integer.valueOf(inputValue);
} catch (NumberFormatException e) {
System.err.println("Must enter integer.");
continue;
}
if (inputInt < 0) {
System.out.println("Must be non-negative");
} else {
printFriends(inputFriend, inputInt);
}
} else {
System.out.println(inputFriend + " not found.");
}
}
}
}
[從遞歸到迭代的方式]可能的重複(http://stackoverflow.com/questions/159590/way-to-go-from-recursion-to-iteration) – azurefrog
請參閱:[爲什麼是「有人可以幫我嗎?「不是一個真正的問題?](http://meta.stackoverflow.com/q/284236) – EJoshuaS